OSDN Git Service

Upgrade to mksh 50.
[android-x86/external-mksh.git] / src / check.pl
1 # $MirOS: src/bin/mksh/check.pl,v 1.36 2014/06/09 13:25:50 tg Exp $
2 # $OpenBSD: th,v 1.1 2013/12/02 20:39:44 millert Exp $
3 #-
4 # Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
5 #               2012, 2013, 2014
6 #       Thorsten Glaser <tg@mirbsd.org>
7 #
8 # Provided that these terms and disclaimer and all copyright notices
9 # are retained or reproduced in an accompanying document, permission
10 # is granted to deal in this work without restriction, including un-
11 # limited rights to use, publicly perform, distribute, sell, modify,
12 # merge, give away, or sublicence.
13 #
14 # This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15 # the utmost extent permitted by applicable law, neither express nor
16 # implied; without malicious intent or gross negligence. In no event
17 # may a licensor, author or contributor be held liable for indirect,
18 # direct, other damage, loss, or other issues arising in any way out
19 # of dealing in the work, even if advised of the possibility of such
20 # damage or existence of a defect, except proven that it results out
21 # of said person's immediate fault when using the work as intended.
22 #-
23 # Example test:
24 #               name: a-test
25 #               description:
26 #                       a test to show how tests are done
27 #               arguments: !-x!-f!
28 #               stdin:
29 #                       echo -n *
30 #                       false
31 #               expected-stdout: !
32 #                       *
33 #               expected-stderr:
34 #                       + echo -n *
35 #                       + false
36 #               expected-exit: 1
37 #               ---
38 #       This runs the test-program (eg, mksh) with the arguments -x and -f,
39 #       standard input is a file containing "echo hi*\nfalse\n". The program
40 #       is expected to produce "hi*" (no trailing newline) on standard output,
41 #       "+ echo hi*\n+false\n" on standard error, and an exit code of 1.
42 #
43 #
44 # Format of test files:
45 # - blank lines and lines starting with # are ignored
46 # - a test file contains a series of tests
47 # - a test is a series of tag:value pairs ended with a "---" line
48 #   (leading/trailing spaces are stripped from the first line of value)
49 # - test tags are:
50 #       Tag                     Flag    Description
51 #       -----                   ----    -----------
52 #       name                    r       The name of the test; should be unique
53 #       description             m       What test does
54 #       arguments               M       Arguments to pass to the program;
55 #                                       default is no arguments.
56 #       script                  m       Value is written to a file which
57 #                                       is passed as an argument to the program
58 #                                       (after the arguments arguments)
59 #       stdin                   m       Value is written to a file which is
60 #                                       used as standard-input for the program;
61 #                                       default is to use /dev/null.
62 #       perl-setup              m       Value is a perl script which is executed
63 #                                       just before the test is run. Try to
64 #                                       avoid using this...
65 #       perl-cleanup            m       Value is a perl script which is executed
66 #                                       just after the test is run. Try to
67 #                                       avoid using this...
68 #       env-setup               M       Value is a list of NAME=VALUE elements
69 #                                       which are put in the environment before
70 #                                       the test is run. If the =VALUE is
71 #                                       missing, NAME is removed from the
72 #                                       environment. Programs are run with
73 #                                       the following minimal environment:
74 #                                           HOME, LD_LIBRARY_PATH, LOCPATH,
75 #                                           LOGNAME, PATH, SHELL, UNIXMODE,
76 #                                           USER
77 #                                       (values taken from the environment of
78 #                                       the test harness).
79 #                                       CYGWIN is set to nodosfilewarning.
80 #                                       ENV is set to /nonexistant.
81 #                                       __progname is set to the -p argument.
82 #                                       __perlname is set to $^X (perlexe).
83 #       file-setup              mps     Used to create files, directories
84 #                                       and symlinks. First word is either
85 #                                       file, dir or symlink; second word is
86 #                                       permissions; this is followed by a
87 #                                       quoted word that is the name of the
88 #                                       file; the end-quote should be followed
89 #                                       by a newline, then the file data
90 #                                       (if any). The first word may be
91 #                                       preceded by a ! to strip the trailing
92 #                                       newline in a symlink.
93 #       file-result             mps     Used to verify a file, symlink or
94 #                                       directory is created correctly.
95 #                                       The first word is either
96 #                                       file, dir or symlink; second word is
97 #                                       expected permissions; third word
98 #                                       is user-id; fourth is group-id;
99 #                                       fifth is "exact" or "pattern"
100 #                                       indicating whether the file contents
101 #                                       which follow is to be matched exactly
102 #                                       or if it is a regular expression.
103 #                                       The fifth argument is the quoted name
104 #                                       of the file that should be created.
105 #                                       The end-quote should be followed
106 #                                       by a newline, then the file data
107 #                                       (if any). The first word may be
108 #                                       preceded by a ! to strip the trailing
109 #                                       newline in the file contents.
110 #                                       The permissions, user and group fields
111 #                                       may be * meaning accept any value.
112 #       time-limit                      Time limit - the program is sent a
113 #                                       SIGKILL N seconds. Default is no
114 #                                       limit.
115 #       expected-fail                   'yes' if the test is expected to fail.
116 #       expected-exit                   expected exit code. Can be a number,
117 #                                       or a C expression using the variables
118 #                                       e, s and w (exit code, termination
119 #                                       signal, and status code).
120 #       expected-stdout         m       What the test should generate on stdout;
121 #                                       default is to expect no output.
122 #       expected-stdout-pattern m       A perl pattern which matches the
123 #                                       expected output.
124 #       expected-stderr         m       What the test should generate on stderr;
125 #                                       default is to expect no output.
126 #       expected-stderr-pattern m       A perl pattern which matches the
127 #                                       expected standard error.
128 #       category                m       Specify a comma separated list of
129 #                                       'categories' of program that the test
130 #                                       is to be run for. A category can be
131 #                                       negated by prefixing the name with a !.
132 #                                       The idea is that some tests in a
133 #                                       test suite may apply to a particular
134 #                                       program version and shouldn't be run
135 #                                       on other versions. The category(s) of
136 #                                       the program being tested can be
137 #                                       specified on the command line.
138 #                                       One category os:XXX is predefined
139 #                                       (XXX is the operating system name,
140 #                                       eg, linux, dec_osf).
141 #       need-ctty                       'yes' if the test needs a ctty, run
142 #                                       with -C regress:no-ctty to disable.
143 # Flag meanings:
144 #       r       tag is required (eg, a test must have a name tag).
145 #       m       value can be multiple lines. Lines must be prefixed with
146 #               a tab. If the value part of the initial tag:value line is
147 #                       - empty: the initial blank line is stripped.
148 #                       - a lone !: the last newline in the value is stripped;
149 #       M       value can be multiple lines (prefixed by a tab) and consists
150 #               of multiple fields, delimited by a field separator character.
151 #               The value must start and end with the f-s-c.
152 #       p       tag takes parameters (used with m).
153 #       s       tag can be used several times.
154
155 # pull EINTR from POSIX.pm or Errno.pm if they exist
156 # otherwise just skip it
157 BEGIN {
158         $EINTR = 0;
159         eval {
160                 require POSIX;
161                 $EINTR = POSIX::EINTR();
162         };
163         if ($@) {
164                 eval {
165                         require Errno;
166                         $EINTR = Errno::EINTR();
167                 } or do {
168                         $EINTR = 0;
169                 };
170         }
171 };
172
173 use Getopt::Std;
174 use Config;
175
176 $os = defined $^O ? $^O : 'unknown';
177
178 ($prog = $0) =~ s#.*/##;
179
180 $Usage = <<EOF ;
181 Usage: $prog [-Pv] [-C cat] [-e e=v] [-p prog] [-s fn] [-T dir] \
182        [-t tmo] name ...
183         -C c    Specify the comma separated list of categories the program
184                 belongs to (see category field).
185         -e e=v  Set the environment variable e to v for all tests
186                 (if no =v is given, the current value is used)
187                 Only one -e option can be given at the moment, sadly.
188         -P      program (-p) string has multiple words, and the program is in
189                 the path (kludge option)
190         -p p    Use p as the program to test
191         -s s    Read tests from file s; if s is a directory, it is recursively
192                 scaned for test files (which end in .t).
193         -T dir  Use dir instead of /tmp to hold temporary files
194         -t t    Use t as default time limit for tests (default is unlimited)
195         -v      Verbose mode: print reason test failed.
196         name    specifies the name of the test(s) to run; if none are
197                 specified, all tests are run.
198 EOF
199
200 # See comment above for flag meanings
201 %test_fields = (
202         'name',                         'r',
203         'description',                  'm',
204         'arguments',                    'M',
205         'script',                       'm',
206         'stdin',                        'm',
207         'perl-setup',                   'm',
208         'perl-cleanup',                 'm',
209         'env-setup',                    'M',
210         'file-setup',                   'mps',
211         'file-result',                  'mps',
212         'time-limit',                   '',
213         'expected-fail',                '',
214         'expected-exit',                '',
215         'expected-stdout',              'm',
216         'expected-stdout-pattern',      'm',
217         'expected-stderr',              'm',
218         'expected-stderr-pattern',      'm',
219         'category',                     'm',
220         'need-ctty',                    '',
221         'need-pass',                    '',
222         );
223 # Filled in by read_test()
224 %internal_test_fields = (
225         ':full-name', 1,                # file:name
226         ':long-name', 1,                # dir/file:lineno:name
227         );
228
229 # Categories of the program under test. Provide the current
230 # os by default.
231 %categories = (
232         "os:$os", '1'
233         );
234
235 $nfailed = 0;
236 $nifailed = 0;
237 $nxfailed = 0;
238 $npassed = 0;
239 $nxpassed = 0;
240
241 %known_tests = ();
242
243 if (!getopts('C:e:Pp:s:T:t:v')) {
244     print STDERR $Usage;
245     exit 1;
246 }
247
248 die "$prog: no program specified (use -p)\n" if !defined $opt_p;
249 die "$prog: no test set specified (use -s)\n" if !defined $opt_s;
250 $test_prog = $opt_p;
251 $verbose = defined $opt_v && $opt_v;
252 $test_set = $opt_s;
253 $temp_base = $opt_T || "/tmp";
254 if (defined $opt_t) {
255     die "$prog: bad -t argument (should be number > 0): $opt_t\n"
256         if $opt_t !~ /^\d+$/ || $opt_t <= 0;
257     $default_time_limit = $opt_t;
258 }
259 $program_kludge = defined $opt_P ? $opt_P : 0;
260
261 if (defined $opt_C) {
262     foreach $c (split(',', $opt_C)) {
263         $c =~ s/\s+//;
264         die "$prog: categories can't be negated on the command line\n"
265             if ($c =~ /^!/);
266         $categories{$c} = 1;
267     }
268 }
269
270 # Note which tests are to be run.
271 %do_test = ();
272 grep($do_test{$_} = 1, @ARGV);
273 $all_tests = @ARGV == 0;
274
275 # Set up a very minimal environment
276 %new_env = ();
277 foreach $env (('HOME', 'LD_LIBRARY_PATH', 'LOCPATH', 'LOGNAME',
278   'PATH', 'SHELL', 'UNIXMODE', 'USER')) {
279     $new_env{$env} = $ENV{$env} if defined $ENV{$env};
280 }
281 $new_env{'CYGWIN'} = 'nodosfilewarning';
282 $new_env{'ENV'} = '/nonexistant';
283 if (($os eq 'VMS') || ($Config{perlpath} =~ m/$Config{_exe}$/i)) {
284         $new_env{'__perlname'} = $Config{perlpath};
285 } else {
286         $new_env{'__perlname'} = $Config{perlpath} . $Config{_exe};
287 }
288 if (defined $opt_e) {
289     # XXX need a way to allow many -e arguments...
290     if ($opt_e =~ /^([a-zA-Z_]\w*)(|=(.*))$/) {
291         $new_env{$1} = $2 eq '' ? $ENV{$1} : $3;
292     } else {
293         die "$0: bad -e argument: $opt_e\n";
294     }
295 }
296 %old_env = %ENV;
297
298 chop($pwd = `pwd 2>/dev/null`);
299 die "$prog: couldn't get current working directory\n" if $pwd eq '';
300 die "$prog: couldn't cd to $pwd - $!\n" if !chdir($pwd);
301
302 die "$prog: couldn't cd to $temp_base - $!\n" if !chdir($temp_base);
303 die "$prog: couldn't get temporary directory base\n" unless -d '.';
304 $temps = sprintf("chk%d-%d.", $$, time());
305 $tempi = 0;
306 until (mkdir(($tempdir = sprintf("%s%03d", $temps, $tempi)), 0700)) {
307     die "$prog: couldn't get temporary directory\n" if $tempi++ >= 999;
308 }
309 die "$prog: couldn't cd to $tempdir - $!\n" if !chdir($tempdir);
310 chop($temp_dir = `pwd 2>/dev/null`);
311 die "$prog: couldn't get temporary directory\n" if $temp_dir eq '';
312 die "$prog: couldn't cd to $pwd - $!\n" if !chdir($pwd);
313
314 if (!$program_kludge) {
315     $test_prog = "$pwd/$test_prog" if substr($test_prog, 0, 1) ne '/';
316     die "$prog: $test_prog is not executable - bye\n"
317         if (! -x $test_prog && $os ne 'os2');
318 }
319
320 @trap_sigs = ('TERM', 'QUIT', 'INT', 'PIPE', 'HUP');
321 @SIG{@trap_sigs} = ('cleanup_exit') x @trap_sigs;
322 $child_kill_ok = 0;
323 $SIG{'ALRM'} = 'catch_sigalrm';
324
325 $| = 1;
326
327 # Create temp files
328 $temps = "${temp_dir}/rts";
329 $tempi = "${temp_dir}/rti";
330 $tempo = "${temp_dir}/rto";
331 $tempe = "${temp_dir}/rte";
332 $tempdir = "${temp_dir}/rtd";
333 mkdir($tempdir, 0700) or die "$prog: couldn't mkdir $tempdir - $!\n";
334
335 if (-d $test_set) {
336     $file_prefix_skip = length($test_set) + 1;
337     $ret = &process_test_dir($test_set);
338 } else {
339     $file_prefix_skip = 0;
340     $ret = &process_test_file($test_set);
341 }
342 &cleanup_exit() if !defined $ret;
343
344 $tot_failed = $nfailed + $nifailed + $nxfailed;
345 $tot_passed = $npassed + $nxpassed;
346 if ($tot_failed || $tot_passed) {
347     print "Total failed: $tot_failed";
348     print " ($nifailed ignored)" if $nifailed;
349     print " ($nxfailed unexpected)" if $nxfailed;
350     print " (as expected)" if $nfailed && !$nxfailed && !$nifailed;
351     print "\nTotal passed: $tot_passed";
352     print " ($nxpassed unexpected)" if $nxpassed;
353     print "\n";
354 }
355
356 &cleanup_exit('ok');
357
358 sub
359 cleanup_exit
360 {
361     local($sig, $exitcode) = ('', 1);
362
363     if ($_[0] eq 'ok') {
364         unless ($nxfailed) {
365                 $exitcode = 0;
366         } else {
367                 $exitcode = 1;
368         }
369     } elsif ($_[0] ne '') {
370         $sig = $_[0];
371     }
372
373     unlink($tempi, $tempo, $tempe, $temps);
374     &scrub_dir($tempdir) if defined $tempdir;
375     rmdir($tempdir) if defined $tempdir;
376     rmdir($temp_dir) if defined $temp_dir;
377
378     if ($sig) {
379         $SIG{$sig} = 'DEFAULT';
380         kill $sig, $$;
381         return;
382     }
383     exit $exitcode;
384 }
385
386 sub
387 catch_sigalrm
388 {
389     $SIG{'ALRM'} = 'catch_sigalrm';
390     kill(9, $child_pid) if $child_kill_ok;
391     $child_killed = 1;
392 }
393
394 sub
395 process_test_dir
396 {
397     local($dir) = @_;
398     local($ret, $file);
399     local(@todo) = ();
400
401     if (!opendir(DIR, $dir)) {
402         print STDERR "$prog: can't open directory $dir - $!\n";
403         return undef;
404     }
405     while (defined ($file = readdir(DIR))) {
406         push(@todo, $file) if $file =~ /^[^.].*\.t$/;
407     }
408     closedir(DIR);
409
410     foreach $file (@todo) {
411         $file = "$dir/$file";
412         if (-d $file) {
413             $ret = &process_test_dir($file);
414         } elsif (-f _) {
415             $ret = &process_test_file($file);
416         }
417         last if !defined $ret;
418     }
419
420     return $ret;
421 }
422
423 sub
424 process_test_file
425 {
426     local($file) = @_;
427     local($ret);
428
429     if (!open(IN, $file)) {
430         print STDERR "$prog: can't open $file - $!\n";
431         return undef;
432     }
433     binmode(IN);
434     while (1) {
435         $ret = &read_test($file, IN, *test);
436         last if !defined $ret || !$ret;
437         next if !$all_tests && !$do_test{$test{'name'}};
438         next if !&category_check(*test);
439         $ret = &run_test(*test);
440         last if !defined $ret;
441     }
442     close(IN);
443
444     return $ret;
445 }
446
447 sub
448 run_test
449 {
450     local(*test) = @_;
451     local($name) = $test{':full-name'};
452
453     return undef if !&scrub_dir($tempdir);
454
455     if (defined $test{'stdin'}) {
456         return undef if !&write_file($tempi, $test{'stdin'});
457         $ifile = $tempi;
458     } else {
459         $ifile = '/dev/null';
460     }
461
462     if (defined $test{'script'}) {
463         return undef if !&write_file($temps, $test{'script'});
464     }
465
466     if (!chdir($tempdir)) {
467         print STDERR "$prog: couldn't cd to $tempdir - $!\n";
468         return undef;
469     }
470
471     if (defined $test{'file-setup'}) {
472         local($i);
473         local($type, $perm, $rest, $c, $len, $name);
474
475         for ($i = 0; $i < $test{'file-setup'}; $i++) {
476             $val = $test{"file-setup:$i"};
477
478             # format is: type perm "name"
479             ($type, $perm, $rest) =
480                 split(' ', $val, 3);
481             $c = substr($rest, 0, 1);
482             $len = index($rest, $c, 1) - 1;
483             $name = substr($rest, 1, $len);
484             $rest = substr($rest, 2 + $len);
485             $perm = oct($perm) if $perm =~ /^\d+$/;
486             if ($type eq 'file') {
487                 return undef if !&write_file($name, $rest);
488                 if (!chmod($perm, $name)) {
489                     print STDERR
490                   "$prog:$test{':long-name'}: can't chmod $perm $name - $!\n";
491                     return undef;
492                 }
493             } elsif ($type eq 'dir') {
494                 if (!mkdir($name, $perm)) {
495                     print STDERR
496                   "$prog:$test{':long-name'}: can't mkdir $perm $name - $!\n";
497                     return undef;
498                 }
499             } elsif ($type eq 'symlink') {
500                 local($oumask) = umask($perm);
501                 local($ret) = symlink($rest, $name);
502                 umask($oumask);
503                 if (!$ret) {
504                     print STDERR
505             "$prog:$test{':long-name'}: couldn't create symlink $name - $!\n";
506                     return undef;
507                 }
508             }
509         }
510     }
511
512     if (defined $test{'perl-setup'}) {
513         eval $test{'perl-setup'};
514         if ($@ ne '') {
515             print STDERR "$prog:$test{':long-name'}: error running perl-setup - $@\n";
516             return undef;
517         }
518     }
519
520     $pid = fork;
521     if (!defined $pid) {
522         print STDERR "$prog: can't fork - $!\n";
523         return undef;
524     }
525     if (!$pid) {
526         @SIG{@trap_sigs} = ('DEFAULT') x @trap_sigs;
527         $SIG{'ALRM'} = 'DEFAULT';
528         if (defined $test{'env-setup'}) {
529             local($var, $val, $i);
530
531             foreach $var (split(substr($test{'env-setup'}, 0, 1),
532                 $test{'env-setup'}))
533             {
534                 $i = index($var, '=');
535                 next if $i == 0 || $var eq '';
536                 if ($i < 0) {
537                     delete $new_env{$var};
538                 } else {
539                     $new_env{substr($var, 0, $i)} = substr($var, $i + 1);
540                 }
541             }
542         }
543         if (!open(STDIN, "< $ifile")) {
544                 print STDERR "$prog: couldn't open $ifile in child - $!\n";
545                 kill('TERM', $$);
546         }
547         binmode(STDIN);
548         if (!open(STDOUT, "> $tempo")) {
549                 print STDERR "$prog: couldn't open $tempo in child - $!\n";
550                 kill('TERM', $$);
551         }
552         binmode(STDOUT);
553         if (!open(STDERR, "> $tempe")) {
554                 print STDOUT "$prog: couldn't open $tempe in child - $!\n";
555                 kill('TERM', $$);
556         }
557         binmode(STDERR);
558         if ($program_kludge) {
559             @argv = split(' ', $test_prog);
560         } else {
561             @argv = ($test_prog);
562         }
563         if (defined $test{'arguments'}) {
564                 push(@argv,
565                      split(substr($test{'arguments'}, 0, 1),
566                            substr($test{'arguments'}, 1)));
567         }
568         push(@argv, $temps) if defined $test{'script'};
569
570         #XXX realpathise, use which/whence -p, or sth. like that
571         #XXX if !$program_kludge, we get by with not doing it for now tho
572         $new_env{'__progname'} = $argv[0];
573
574         # The following doesn't work with perl5...  Need to do it explicitly - yuck.
575         #%ENV = %new_env;
576         foreach $k (keys(%ENV)) {
577             delete $ENV{$k};
578         }
579         $ENV{$k} = $v while ($k,$v) = each %new_env;
580
581         exec { $argv[0] } @argv;
582         print STDERR "$prog: couldn't execute $test_prog - $!\n";
583         kill('TERM', $$);
584         exit(95);
585     }
586     $child_pid = $pid;
587     $child_killed = 0;
588     $child_kill_ok = 1;
589     alarm($test{'time-limit'}) if defined $test{'time-limit'};
590     while (1) {
591         $xpid = waitpid($pid, 0);
592         $child_kill_ok = 0;
593         if ($xpid < 0) {
594             if ($EINTR) {
595                 next if $! == $EINTR;
596             }
597             print STDERR "$prog: error waiting for child - $!\n";
598             return undef;
599         }
600         last;
601     }
602     $status = $?;
603     alarm(0) if defined $test{'time-limit'};
604
605     $failed = 0;
606     $why = '';
607
608     if ($child_killed) {
609         $failed = 1;
610         $why .= "\ttest timed out (limit of $test{'time-limit'} seconds)\n";
611     }
612
613     $ret = &eval_exit($test{'long-name'}, $status, $test{'expected-exit'});
614     return undef if !defined $ret;
615     if (!$ret) {
616         local($expl);
617
618         $failed = 1;
619         if (($status & 0xff) == 0x7f) {
620             $expl = "stopped";
621         } elsif (($status & 0xff)) {
622             $expl = "signal " . ($status & 0x7f);
623         } else {
624             $expl = "exit-code " . (($status >> 8) & 0xff);
625         }
626         $why .=
627         "\tunexpected exit status $status ($expl), expected $test{'expected-exit'}\n";
628     }
629
630     $tmp = &check_output($test{'long-name'}, $tempo, 'stdout',
631                 $test{'expected-stdout'}, $test{'expected-stdout-pattern'});
632     return undef if !defined $tmp;
633     if ($tmp ne '') {
634         $failed = 1;
635         $why .= $tmp;
636     }
637
638     $tmp = &check_output($test{'long-name'}, $tempe, 'stderr',
639                 $test{'expected-stderr'}, $test{'expected-stderr-pattern'});
640     return undef if !defined $tmp;
641     if ($tmp ne '') {
642         $failed = 1;
643         $why .= $tmp;
644     }
645
646     $tmp = &check_file_result(*test);
647     return undef if !defined $tmp;
648     if ($tmp ne '') {
649         $failed = 1;
650         $why .= $tmp;
651     }
652
653     if (defined $test{'perl-cleanup'}) {
654         eval $test{'perl-cleanup'};
655         if ($@ ne '') {
656             print STDERR "$prog:$test{':long-name'}: error running perl-cleanup - $@\n";
657             return undef;
658         }
659     }
660
661     if (!chdir($pwd)) {
662         print STDERR "$prog: couldn't cd to $pwd - $!\n";
663         return undef;
664     }
665
666     if ($failed) {
667         if (!$test{'expected-fail'}) {
668             if ($test{'need-pass'}) {
669                 print "FAIL $name\n";
670                 $nxfailed++;
671             } else {
672                 print "FAIL $name (ignored)\n";
673                 $nifailed++;
674             }
675         } else {
676             print "fail $name (as expected)\n";
677             $nfailed++;
678         }
679         $why = "\tDescription"
680                 . &wrap_lines($test{'description'}, " (missing)\n")
681                 . $why;
682     } elsif ($test{'expected-fail'}) {
683         print "PASS $name (unexpectedly)\n";
684         $nxpassed++;
685     } else {
686         print "pass $name\n";
687         $npassed++;
688     }
689     print $why if $verbose;
690     return 0;
691 }
692
693 sub
694 category_check
695 {
696     local(*test) = @_;
697     local($c);
698
699     return 0 if ($test{'need-ctty'} && defined $categories{'regress:no-ctty'});
700     return 1 if (!defined $test{'category'});
701     local($ok) = 0;
702     foreach $c (split(',', $test{'category'})) {
703         $c =~ s/\s+//;
704         if ($c =~ /^!/) {
705             $c = $';
706             return 0 if (defined $categories{$c});
707             $ok = 1;
708         } else {
709             $ok = 1 if (defined $categories{$c});
710         }
711     }
712     return $ok;
713 }
714
715 sub
716 scrub_dir
717 {
718     local($dir) = @_;
719     local(@todo) = ();
720     local($file);
721
722     if (!opendir(DIR, $dir)) {
723         print STDERR "$prog: couldn't open directory $dir - $!\n";
724         return undef;
725     }
726     while (defined ($file = readdir(DIR))) {
727         push(@todo, $file) if $file ne '.' && $file ne '..';
728     }
729     closedir(DIR);
730     foreach $file (@todo) {
731         $file = "$dir/$file";
732         if (-d $file) {
733             return undef if !&scrub_dir($file);
734             if (!rmdir($file)) {
735                 print STDERR "$prog: couldn't rmdir $file - $!\n";
736                 return undef;
737             }
738         } else {
739             if (!unlink($file)) {
740                 print STDERR "$prog: couldn't unlink $file - $!\n";
741                 return undef;
742             }
743         }
744     }
745     return 1;
746 }
747
748 sub
749 write_file
750 {
751     local($file, $str) = @_;
752
753     if (!open(TEMP, "> $file")) {
754         print STDERR "$prog: can't open $file - $!\n";
755         return undef;
756     }
757     binmode(TEMP);
758     print TEMP $str;
759     if (!close(TEMP)) {
760         print STDERR "$prog: error writing $file - $!\n";
761         return undef;
762     }
763     return 1;
764 }
765
766 sub
767 check_output
768 {
769     local($name, $file, $what, $expect, $expect_pat) = @_;
770     local($got) = '';
771     local($why) = '';
772     local($ret);
773
774     if (!open(TEMP, "< $file")) {
775         print STDERR "$prog:$name($what): couldn't open $file after running program - $!\n";
776         return undef;
777     }
778     binmode(TEMP);
779     while (<TEMP>) {
780         $got .= $_;
781     }
782     close(TEMP);
783     return compare_output($name, $what, $expect, $expect_pat, $got);
784 }
785
786 sub
787 compare_output
788 {
789     local($name, $what, $expect, $expect_pat, $got) = @_;
790     local($why) = '';
791
792     if (defined $expect_pat) {
793         $_ = $got;
794         $ret = eval "$expect_pat";
795         if ($@ ne '') {
796             print STDERR "$prog:$name($what): error evaluating $what pattern: $expect_pat - $@\n";
797             return undef;
798         }
799         if (!$ret) {
800             $why = "\tunexpected $what - wanted pattern";
801             $why .= &wrap_lines($expect_pat);
802             $why .= "\tgot";
803             $why .= &wrap_lines($got);
804         }
805     } else {
806         $expect = '' if !defined $expect;
807         if ($got ne $expect) {
808             $why .= "\tunexpected $what - " . &first_diff($expect, $got) . "\n";
809             $why .= "\twanted";
810             $why .= &wrap_lines($expect);
811             $why .= "\tgot";
812             $why .= &wrap_lines($got);
813         }
814     }
815     return $why;
816 }
817
818 sub
819 wrap_lines
820 {
821     local($str, $empty) = @_;
822     local($nonl) = substr($str, -1, 1) ne "\n";
823
824     return (defined $empty ? $empty : " nothing\n") if $str eq '';
825     substr($str, 0, 0) = ":\n";
826     $str =~ s/\n/\n\t\t/g;
827     if ($nonl) {
828         $str .= "\n\t[incomplete last line]\n";
829     } else {
830         chop($str);
831         chop($str);
832     }
833     return $str;
834 }
835
836 sub
837 first_diff
838 {
839     local($exp, $got) = @_;
840     local($lineno, $char) = (1, 1);
841     local($i, $exp_len, $got_len);
842     local($ce, $cg);
843
844     $exp_len = length($exp);
845     $got_len = length($got);
846     if ($exp_len != $got_len) {
847         if ($exp_len < $got_len) {
848             if (substr($got, 0, $exp_len) eq $exp) {
849                 return "got too much output";
850             }
851         } elsif (substr($exp, 0, $got_len) eq $got) {
852             return "got too little output";
853         }
854     }
855     for ($i = 0; $i < $exp_len; $i++) {
856         $ce = substr($exp, $i, 1);
857         $cg = substr($got, $i, 1);
858         last if $ce ne $cg;
859         $char++;
860         if ($ce eq "\n") {
861             $lineno++;
862             $char = 1;
863         }
864     }
865     return "first difference: line $lineno, char $char (wanted '"
866         . &format_char($ce) . "', got '"
867         . &format_char($cg) . "'";
868 }
869
870 sub
871 format_char
872 {
873     local($ch, $s);
874
875     $ch = ord($_[0]);
876     if ($ch == 10) {
877         return '\n';
878     } elsif ($ch == 13) {
879         return '\r';
880     } elsif ($ch == 8) {
881         return '\b';
882     } elsif ($ch == 9) {
883         return '\t';
884     } elsif ($ch > 127) {
885         $ch -= 127;
886         $s = "M-";
887     } else {
888         $s = '';
889     }
890     if ($ch < 32) {
891         $s .= '^';
892         $ch += ord('@');
893     } elsif ($ch == 127) {
894         return $s . "^?";
895     }
896     return $s . sprintf("%c", $ch);
897 }
898
899 sub
900 eval_exit
901 {
902     local($name, $status, $expect) = @_;
903     local($expr);
904     local($w, $e, $s) = ($status, ($status >> 8) & 0xff, $status & 0x7f);
905
906     $e = -1000 if $status & 0xff;
907     $s = -1000 if $s == 0x7f;
908     if (!defined $expect) {
909         $expr = '$w == 0';
910     } elsif ($expect =~ /^(|-)\d+$/) {
911         $expr = "\$e == $expect";
912     } else {
913         $expr = $expect;
914         $expr =~ s/\b([wse])\b/\$$1/g;
915         $expr =~ s/\b(SIG[A-Z][A-Z0-9]*)\b/&$1/g;
916     }
917     $w = eval $expr;
918     if ($@ ne '') {
919         print STDERR "$prog:$test{':long-name'}: bad expected-exit expression: $expect ($@)\n";
920         return undef;
921     }
922     return $w;
923 }
924
925 sub
926 read_test
927 {
928     local($file, $in, *test) = @_;
929     local($field, $val, $flags, $do_chop, $need_redo, $start_lineno);
930     local(%cnt, $sfield);
931
932     %test = ();
933     %cnt = ();
934     while (<$in>) {
935         chop;
936         next if /^\s*$/;
937         next if /^ *#/;
938         last if /^\s*---\s*$/;
939         $start_lineno = $. if !defined $start_lineno;
940         if (!/^([-\w]+):\s*(|\S|\S.*\S)\s*$/) {
941             print STDERR "$prog:$file:$.: unrecognised line \"$_\"\n";
942             return undef;
943         }
944         ($field, $val) = ($1, $2);
945         $sfield = $field;
946         $flags = $test_fields{$field};
947         if (!defined $flags) {
948             print STDERR "$prog:$file:$.: unrecognised field \"$field\"\n";
949             return undef;
950         }
951         if ($flags =~ /s/) {
952             local($cnt) = $cnt{$field}++;
953             $test{$field} = $cnt{$field};
954             $cnt = 0 if $cnt eq '';
955             $sfield .= ":$cnt";
956         } elsif (defined $test{$field}) {
957             print STDERR "$prog:$file:$.: multiple \"$field\" fields\n";
958             return undef;
959         }
960         $do_chop = $flags !~ /m/;
961         $need_redo = 0;
962         if ($val eq '' || $val eq '!' || $flags =~ /p/) {
963             if ($flags =~ /[Mm]/) {
964                 if ($flags =~ /p/) {
965                     if ($val =~ /^!/) {
966                         $do_chop = 1;
967                         $val = $';
968                     } else {
969                         $do_chop = 0;
970                     }
971                     if ($val eq '') {
972                         print STDERR
973                 "$prog:$file:$.: no parameters given for field \"$field\"\n";
974                         return undef;
975                     }
976                 } else {
977                     if ($val eq '!') {
978                         $do_chop = 1;
979                     }
980                     $val = '';
981                 }
982                 while (<$in>) {
983                     last if !/^\t/;
984                     $val .= $';
985                 }
986                 chop $val if $do_chop;
987                 $do_chop = 1;
988                 $need_redo = 1;
989
990                 # Syntax check on fields that can several instances
991                 # (can give useful line numbers this way)
992
993                 if ($field eq 'file-setup') {
994                     local($type, $perm, $rest, $c, $len, $name);
995
996                     # format is: type perm "name"
997                     if ($val !~ /^[ \t]*(\S+)[ \t]+(\S+)[ \t]+([^ \t].*)/) {
998                         print STDERR
999                     "$prog:$file:$.: bad parameter line for file-setup field\n";
1000                         return undef;
1001                     }
1002                     ($type, $perm, $rest) = ($1, $2, $3);
1003                     if ($type !~ /^(file|dir|symlink)$/) {
1004                         print STDERR
1005                     "$prog:$file:$.: bad file type for file-setup: $type\n";
1006                         return undef;
1007                     }
1008                     if ($perm !~ /^\d+$/) {
1009                         print STDERR
1010                     "$prog:$file:$.: bad permissions for file-setup: $type\n";
1011                         return undef;
1012                     }
1013                     $c = substr($rest, 0, 1);
1014                     if (($len = index($rest, $c, 1) - 1) <= 0) {
1015                         print STDERR
1016     "$prog:$file:$.: missing end quote for file name in file-setup: $rest\n";
1017                         return undef;
1018                     }
1019                     $name = substr($rest, 1, $len);
1020                     if ($name =~ /^\// || $name =~ /(^|\/)\.\.(\/|$)/) {
1021                         # Note: this is not a security thing - just a sanity
1022                         # check - a test can still use symlinks to get at files
1023                         # outside the test directory.
1024                         print STDERR
1025 "$prog:$file:$.: file name in file-setup is absolute or contains ..: $name\n";
1026                         return undef;
1027                     }
1028                 }
1029                 if ($field eq 'file-result') {
1030                     local($type, $perm, $uid, $gid, $matchType,
1031                           $rest, $c, $len, $name);
1032
1033                     # format is: type perm uid gid matchType "name"
1034                     if ($val !~ /^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S.*)/) {
1035                         print STDERR
1036                     "$prog:$file:$.: bad parameter line for file-result field\n";
1037                         return undef;
1038                     }
1039                     ($type, $perm, $uid, $gid, $matchType, $rest)
1040                         = ($1, $2, $3, $4, $5, $6);
1041                     if ($type !~ /^(file|dir|symlink)$/) {
1042                         print STDERR
1043                     "$prog:$file:$.: bad file type for file-result: $type\n";
1044                         return undef;
1045                     }
1046                     if ($perm !~ /^\d+$/ && $perm ne '*') {
1047                         print STDERR
1048                     "$prog:$file:$.: bad permissions for file-result: $perm\n";
1049                         return undef;
1050                     }
1051                     if ($uid !~ /^\d+$/ && $uid ne '*') {
1052                         print STDERR
1053                     "$prog:$file:$.: bad user-id for file-result: $uid\n";
1054                         return undef;
1055                     }
1056                     if ($gid !~ /^\d+$/ && $gid ne '*') {
1057                         print STDERR
1058                     "$prog:$file:$.: bad group-id for file-result: $gid\n";
1059                         return undef;
1060                     }
1061                     if ($matchType !~ /^(exact|pattern)$/) {
1062                         print STDERR
1063                 "$prog:$file:$.: bad match type for file-result: $matchType\n";
1064                         return undef;
1065                     }
1066                     $c = substr($rest, 0, 1);
1067                     if (($len = index($rest, $c, 1) - 1) <= 0) {
1068                         print STDERR
1069     "$prog:$file:$.: missing end quote for file name in file-result: $rest\n";
1070                         return undef;
1071                     }
1072                     $name = substr($rest, 1, $len);
1073                     if ($name =~ /^\// || $name =~ /(^|\/)\.\.(\/|$)/) {
1074                         # Note: this is not a security thing - just a sanity
1075                         # check - a test can still use symlinks to get at files
1076                         # outside the test directory.
1077                         print STDERR
1078 "$prog:$file:$.: file name in file-result is absolute or contains ..: $name\n";
1079                         return undef;
1080                     }
1081                 }
1082             } elsif ($val eq '') {
1083                 print STDERR
1084                     "$prog:$file:$.: no value given for field \"$field\"\n";
1085                 return undef;
1086             }
1087         }
1088         $val .= "\n" if !$do_chop;
1089         $test{$sfield} = $val;
1090         redo if $need_redo;
1091     }
1092     if ($_ eq '') {
1093         if (%test) {
1094             print STDERR
1095               "$prog:$file:$start_lineno: end-of-file while reading test\n";
1096             return undef;
1097         }
1098         return 0;
1099     }
1100
1101     while (($field, $val) = each %test_fields) {
1102         if ($val =~ /r/ && !defined $test{$field}) {
1103             print STDERR
1104               "$prog:$file:$start_lineno: required field \"$field\" missing\n";
1105             return undef;
1106         }
1107     }
1108
1109     $test{':full-name'} = substr($file, $file_prefix_skip) . ":$test{'name'}";
1110     $test{':long-name'} = "$file:$start_lineno:$test{'name'}";
1111
1112     # Syntax check on specific fields
1113     if (defined $test{'expected-fail'}) {
1114         if ($test{'expected-fail'} !~ /^(yes|no)$/) {
1115             print STDERR
1116               "$prog:$test{':long-name'}: bad value for expected-fail field\n";
1117             return undef;
1118         }
1119         $test{'expected-fail'} = $1 eq 'yes';
1120     } else {
1121         $test{'expected-fail'} = 0;
1122     }
1123     if (defined $test{'need-ctty'}) {
1124         if ($test{'need-ctty'} !~ /^(yes|no)$/) {
1125             print STDERR
1126               "$prog:$test{':long-name'}: bad value for need-ctty field\n";
1127             return undef;
1128         }
1129         $test{'need-ctty'} = $1 eq 'yes';
1130     } else {
1131         $test{'need-ctty'} = 0;
1132     }
1133     if (defined $test{'need-pass'}) {
1134         if ($test{'need-pass'} !~ /^(yes|no)$/) {
1135             print STDERR
1136               "$prog:$test{':long-name'}: bad value for need-pass field\n";
1137             return undef;
1138         }
1139         $test{'need-pass'} = $1 eq 'yes';
1140     } else {
1141         $test{'need-pass'} = 1;
1142     }
1143     if (defined $test{'arguments'}) {
1144         local($firstc) = substr($test{'arguments'}, 0, 1);
1145
1146         if (substr($test{'arguments'}, -1, 1) ne $firstc) {
1147             print STDERR "$prog:$test{':long-name'}: arguments field doesn't start and end with the same character\n";
1148             return undef;
1149         }
1150     }
1151     if (defined $test{'env-setup'}) {
1152         local($firstc) = substr($test{'env-setup'}, 0, 1);
1153
1154         if (substr($test{'env-setup'}, -1, 1) ne $firstc) {
1155             print STDERR "$prog:$test{':long-name'}: env-setup field doesn't start and end with the same character\n";
1156             return undef;
1157         }
1158     }
1159     if (defined $test{'expected-exit'}) {
1160         local($val) = $test{'expected-exit'};
1161
1162         if ($val =~ /^(|-)\d+$/) {
1163             if ($val < 0 || $val > 255) {
1164                 print STDERR "$prog:$test{':long-name'}: expected-exit value $val not in 0..255\n";
1165                 return undef;
1166             }
1167         } elsif ($val !~ /^([\s<>+-=*%\/&|!()]|\b[wse]\b|\bSIG[A-Z][A-Z0-9]*\b)+$/) {
1168             print STDERR "$prog:$test{':long-name'}: bad expected-exit expression: $val\n";
1169             return undef;
1170         }
1171     } else {
1172         $test{'expected-exit'} = 0;
1173     }
1174     if (defined $test{'expected-stdout'}
1175         && defined $test{'expected-stdout-pattern'})
1176     {
1177         print STDERR "$prog:$test{':long-name'}: can't use both expected-stdout and expected-stdout-pattern\n";
1178         return undef;
1179     }
1180     if (defined $test{'expected-stderr'}
1181         && defined $test{'expected-stderr-pattern'})
1182     {
1183         print STDERR "$prog:$test{':long-name'}: can't use both expected-stderr and expected-stderr-pattern\n";
1184         return undef;
1185     }
1186     if (defined $test{'time-limit'}) {
1187         if ($test{'time-limit'} !~ /^\d+$/ || $test{'time-limit'} == 0) {
1188             print STDERR
1189               "$prog:$test{':long-name'}: bad value for time-limit field\n";
1190             return undef;
1191         }
1192     } elsif (defined $default_time_limit) {
1193         $test{'time-limit'} = $default_time_limit;
1194     }
1195
1196     if (defined $known_tests{$test{'name'}}) {
1197         print STDERR "$prog:$test{':long-name'}: warning: duplicate test name ${test{'name'}}\n";
1198     }
1199     $known_tests{$test{'name'}} = 1;
1200
1201     return 1;
1202 }
1203
1204 sub
1205 tty_msg
1206 {
1207     local($msg) = @_;
1208
1209     open(TTY, "> /dev/tty") || return 0;
1210     print TTY $msg;
1211     close(TTY);
1212     return 1;
1213 }
1214
1215 sub
1216 never_called_funcs
1217 {
1218         return 0;
1219         &tty_msg("hi\n");
1220         &never_called_funcs();
1221         &catch_sigalrm();
1222         $old_env{'foo'} = 'bar';
1223         $internal_test_fields{'foo'} = 'bar';
1224 }
1225
1226 sub
1227 check_file_result
1228 {
1229     local(*test) = @_;
1230
1231     return '' if (!defined $test{'file-result'});
1232
1233     local($why) = '';
1234     local($i);
1235     local($type, $perm, $uid, $gid, $rest, $c, $len, $name);
1236     local(@stbuf);
1237
1238     for ($i = 0; $i < $test{'file-result'}; $i++) {
1239         $val = $test{"file-result:$i"};
1240
1241         # format is: type perm "name"
1242         ($type, $perm, $uid, $gid, $matchType, $rest) =
1243             split(' ', $val, 6);
1244         $c = substr($rest, 0, 1);
1245         $len = index($rest, $c, 1) - 1;
1246         $name = substr($rest, 1, $len);
1247         $rest = substr($rest, 2 + $len);
1248         $perm = oct($perm) if $perm =~ /^\d+$/;
1249
1250         @stbuf = lstat($name);
1251         if (!@stbuf) {
1252             $why .= "\texpected $type \"$name\" not created\n";
1253             next;
1254         }
1255         if ($perm ne '*' && ($stbuf[2] & 07777) != $perm) {
1256             $why .= "\t$type \"$name\" has unexpected permissions\n";
1257             $why .= sprintf("\t\texpected 0%o, found 0%o\n",
1258                     $perm, $stbuf[2] & 07777);
1259         }
1260         if ($uid ne '*' && $stbuf[4] != $uid) {
1261             $why .= "\t$type \"$name\" has unexpected user-id\n";
1262             $why .= sprintf("\t\texpected %d, found %d\n",
1263                     $uid, $stbuf[4]);
1264         }
1265         if ($gid ne '*' && $stbuf[5] != $gid) {
1266             $why .= "\t$type \"$name\" has unexpected group-id\n";
1267             $why .= sprintf("\t\texpected %d, found %d\n",
1268                     $gid, $stbuf[5]);
1269         }
1270
1271         if ($type eq 'file') {
1272             if (-l _ || ! -f _) {
1273                 $why .= "\t$type \"$name\" is not a regular file\n";
1274             } else {
1275                 local $tmp = &check_output($test{'long-name'}, $name,
1276                             "$type contents in \"$name\"",
1277                             $matchType eq 'exact' ? $rest : undef
1278                             $matchType eq 'pattern' ? $rest : undef);
1279                 return undef if (!defined $tmp);
1280                 $why .= $tmp;
1281             }
1282         } elsif ($type eq 'dir') {
1283             if ($rest !~ /^\s*$/) {
1284                 print STDERR "$prog:$test{':long-name'}: file-result test for directory $name should not have content specified\n";
1285                 return undef;
1286             }
1287             if (-l _ || ! -d _) {
1288                 $why .= "\t$type \"$name\" is not a directory\n";
1289             }
1290         } elsif ($type eq 'symlink') {
1291             if (!-l _) {
1292                 $why .= "\t$type \"$name\" is not a symlink\n";
1293             } else {
1294                 local $content = readlink($name);
1295                 if (!defined $content) {
1296                     print STDERR "$prog:$test{':long-name'}: file-result test for $type $name failed - could not readlink - $!\n";
1297                     return undef;
1298                 }
1299                 local $tmp = &compare_output($test{'long-name'},
1300                             "$type contents in \"$name\"",
1301                             $matchType eq 'exact' ? $rest : undef
1302                             $matchType eq 'pattern' ? $rest : undef);
1303                 return undef if (!defined $tmp);
1304                 $why .= $tmp;
1305             }
1306         }
1307     }
1308
1309     return $why;
1310 }
1311
1312 sub
1313 HELP_MESSAGE
1314 {
1315     print STDERR $Usage;
1316     exit 0;
1317 }