fix bugs, add boolean flag to identify coercion variables
[ghc-hetmet.git] / utils / runstdtest / runstdtest.prl
1 #
2 # The perl script requires the following variables to be bound
3 # to something meaningful before it will operate correctly:
4 #   
5 #   DEFAULT_TMPDIR
6 #   CONTEXT_DIFF
7 #   RM
8 #
9 # Given:
10 #       * a program to run (1st arg)
11 #       * some "command-line opts" ( -O<opt1> -O<opt2> ... )
12 #           [default: anything on the cmd line this script doesn't recognise ]
13 #         the first opt not starting w/ "-" is taken to be an input
14 #         file and (if it exists) is grepped for "what's going on here"
15 #         comments (^-- !!!).
16 #       * a file to feed to stdin ( -i<file> ) [default: /dev/null ]
17 #       * a "time" command to use (-t <cmd>).
18 #
19 #       * alternatively, a "-script <script>" argument says: run the
20 #         named Bourne-shell script to do the test.  It's passed the
21 #         pgm-to-run as the one-and-only arg.
22 #
23 # Run the program with those options and that input, and check:
24 # if we get...
25
26 #       * an expected exit status ( -x <val> ) [ default 0 ]
27 #       * expected output on stdout ( -o1 <file> ) [ default /dev/null ]
28 #               ( we'll accept one of several...)
29 #       * expected output on stderr ( -o2 <file> ) [ default /dev/null ]
30 #               ( we'll accept one of several...)
31 #
32 #       (if the expected-output files' names end in .Z, then
33 #        they are uncompressed before doing the comparison)
34
35 # (This is supposed to be a "prettier" replacement for runstdtest.)
36 #
37 #       Flags
38 #       ~~~~~
39 #       -accept-output  replace output files with the ones actually generated by running
40 #                       the program
41 #
42 ($Pgm = $0) =~ s|.*/||;
43 $Verbose = 0;
44 $SaveStderr = 0;
45 $SaveStdout = 0;
46 $Status = 0;
47 @PgmArgs = ();
48 $PgmFail=0;
49 $PgmExitStatus = 0;
50 $PgmStdinFile  = '/dev/null';
51 if ( $ENV{'TMPDIR'} ) { # where to make tmp file names
52     $TmpPrefix = $ENV{'TMPDIR'};
53 } else {
54     $TmpPrefix ="$DEFAULT_TMPDIR";
55     $ENV{'TMPDIR'} = "$DEFAULT_TMPDIR"; # set the env var as well
56 }
57 # If this is Cygwin, ignore eol and CR characters.
58 # Perhaps required for MSYS too, although the cygpath
59 # bit is hopefully unnecessary.
60 if ( `uname | grep CYGWIN` ) {
61     $CONTEXT_DIFF=$CONTEXT_DIFF . " --strip-trailing-cr" ;
62     $TmpPrefix = `cygpath -m $TmpPrefix | tr -d \\\\n`;
63 }
64 $ScriptFile = "$TmpPrefix/run_me$$";
65 $DefaultStdoutFile = "$TmpPrefix/no_stdout$$"; # can't use /dev/null (e.g. Alphas)
66 $DefaultStderrFile = "$TmpPrefix/no_stderr$$";
67 @PgmStdoutFile = ();
68 @PgmStderrFile = ();
69 $PreScript = '';
70 $PostScript = '';
71 $TimeCmd = 'time';
72 $StatsFile = "$TmpPrefix/stats$$";
73 $CachegrindStats = "cachegrind.out.summary";
74 $SysSpecificTiming = '';
75 $Cachegrind = 'no';
76
77 die "$Pgm: program to run not given as first argument\n" if $#ARGV < 0;
78 $ToRun = $ARGV[0]; shift(@ARGV);
79 # avoid picking up same-named thing from somewhere else on $PATH...
80 $ToRun = "./$ToRun" if -e "./$ToRun";
81
82 arg: while ($_ = $ARGV[0]) {
83     shift(@ARGV);
84     
85     /^--$/      && do { # let anything past after --
86                         push(@PgmArgs, @ARGV);
87                         last arg; };
88
89     /^-v$/             && do { $Verbose = 1; next arg; };
90     /^-accept-output-stderr$/ && do { $SaveStderr = 1; next arg; };
91     /^-accept-output-stdout$/ && do { $SaveStdout = 1; next arg; };
92     /^-accept-output$/        && do { $SaveStdout = 1; $SaveStderr = 1; next arg; };
93
94     /^-O(.*)/   && do { push(@PgmArgs, &grab_arg_arg('-O',$1)); next arg; };
95     /^-i(.*)/   && do { $PgmStdinFile = &grab_arg_arg('-i',$1);
96                         $Status++,
97                         print STDERR "$Pgm: bogus -i input file: $PgmStdinFile\n"
98                             if $PgmStdinFile !~ /^\/dev\/.*$/ && ! -f $PgmStdinFile;
99                         next arg; };
100     /^-fail/    && do { $PgmFail=1; next arg; };
101     /^-x(.*)/   && do { $PgmExitStatus = &grab_arg_arg('-x',$1);
102                         $Status++ ,
103                         print STDERR "$Pgm: bogus -x expected exit status: $PgmExitStatus\n"
104                             if $PgmExitStatus !~ /^\d+$/;
105                         next arg; };
106     /^-o1(.*)/  && do { $out_file = &grab_arg_arg('-o1',$1);
107                         push(@PgmStdoutFile, $out_file);
108                         next arg; };
109     /^-o2(.*)/  && do { $out_file = &grab_arg_arg('-o2',$1);
110                         push(@PgmStderrFile, $out_file);
111                         next arg; };
112     /^-prescript(.*)/  && do { $PreScript = &grab_arg_arg('-prescript',$1);
113                                 next arg; };
114     /^-postscript(.*)/ && do { $PostScript = &grab_arg_arg('-postscript',$1);
115                                 next arg; };
116     /^-script/ && do { print STDERR "$Pgm: -script argument is obsolete;\nUse -prescript and -postscript instead.\n";
117                     $Status++;
118                     next arg; };
119     /^-(ghc|hbc)-timing$/ && do { $SysSpecificTiming = $1;
120                                   next arg; };
121     /^-cachegrind$/ && do { $SysSpecificTiming = 'ghc-instrs';
122                             $Cachegrind = 'yes'; 
123                             next arg };
124     /^-t(.*)/   && do { $TimeCmd = &grab_arg_arg('-t', $1); next arg; };
125
126     # anything else is taken to be a pgm arg
127     push(@PgmArgs, $_);
128 }
129
130 foreach $out_file ( @PgmStdoutFile ) {
131     if ( ! -f $out_file && !$SaveStdout ) {
132             print STDERR "$Pgm: warning: expected-stdout file missing: $out_file\n";
133             pop(@PgmStdoutFile);
134     }
135 }
136
137 foreach $out_file ( @PgmStderrFile ) {
138     if ( ! -f $out_file && !$SaveStderr ) {
139             print STDERR "$Pgm: warning: expected-stderr file missing: $out_file\n";
140             pop(@PgmStderrFile);
141     }
142 }
143
144 exit 1 if $Status;
145
146 # add on defaults if none specified
147 @PgmStdoutFile = ( $DefaultStdoutFile ) if $#PgmStdoutFile < 0;
148 @PgmStderrFile = ( $DefaultStderrFile ) if $#PgmStderrFile < 0;
149
150 # tidy up the pgm args:
151 # (1) look for the "first input file"
152 #     and grep it for "interesting" comments (-- !!! )
153 # (2) quote any args w/ whitespace in them.
154 $grep_done = 0;
155 foreach $a ( @PgmArgs ) {
156     if (! $grep_done && $a !~ /^-/ && -f $a) {
157         print `egrep "^--[ ]?!!!" $a`;
158         $grep_done = 1;
159     }
160     if ($a =~ /\s/ || $a =~ /'/) {
161         $a =~ s/'/\\'/g;    # backslash the quotes;
162         $a = "\"$a\"";      # quote the arg
163     }
164 }
165
166 # deal with system-specific timing options
167 $TimingMagic = '';
168 if ( $SysSpecificTiming =~ /^ghc/ ) {
169     $TimingMagic = "+RTS -S$StatsFile -RTS"
170 } elsif ( $SysSpecificTiming eq 'hbc' ) {
171     $TimingMagic = "-S$StatsFile";
172 }
173
174 if ($PreScript ne '') {
175     local($to_do);
176     $PreScriptLines = `cat $PreScript`;
177     $PreScriptLines =~ s/\r//g;
178 } else {
179     $PreScriptLines = '';
180 }
181
182 if ($PostScript ne '') {
183     local($to_do);
184     $PostScriptLines = `cat $PostScript`;
185     $PostScriptLines =~ s/\r//g;
186     $* = 1;
187     $PostScriptLines =~ s#\$o1#$TmpPrefix/runtest$$.1#g;
188     $PostScriptLines =~ s#\$o2#$TmpPrefix/runtest$$.2#g;
189 } else {
190     $PostScriptLines = '';
191 }
192
193 # OK, so we're gonna do the normal thing...
194
195 if ($Cachegrind eq 'yes') {
196   $CachegrindPrefix = "valgrind --tool=cachegrind --log-fd=9 9>$CachegrindStats";
197 } else {
198   $CachegrindPrefix = '';
199 }
200
201 $Script = <<EOSCRIPT;
202 #! /bin/sh
203 myexit=0
204 diffsShown=0
205 rm -f $DefaultStdoutFile $DefaultStderrFile
206 cat /dev/null > $DefaultStdoutFile
207 cat /dev/null > $DefaultStderrFile
208 $PreScriptLines
209 $SpixifyLine1
210 echo $TimeCmd /bin/sh -c \'$CachegrindPrefix $ToRun $TimingMagic @PgmArgs < $PgmStdinFile | dos2unix 1> $TmpPrefix/runtest$$.1 2> $TmpPrefix/runtest$$.2 3> $TmpPrefix/runtest$$.3\'
211 $TimeCmd /bin/sh -c \'$CachegrindPrefix $ToRun $TimingMagic @PgmArgs < $PgmStdinFile | dos2unix 1> $TmpPrefix/runtest$$.1 2> $TmpPrefix/runtest$$.2 3> $TmpPrefix/runtest$$.3\'
212 progexit=\$?
213 if [ \$progexit -eq 0 ] && [ $PgmFail -ne 0 ]; then
214     echo $ToRun @PgmArgs \\< $PgmStdinFile
215     echo "****" expected a failure, but was successful
216     myexit=1
217 fi
218 if [ \$progexit -ne $PgmExitStatus ] && [ $PgmFail -eq 0 ]; then
219     echo $ToRun @PgmArgs \\< $PgmStdinFile
220     echo "****" expected exit status $PgmExitStatus not seen \\; got \$progexit
221     myexit=1
222 else
223     $PostScriptLines
224     hit='NO'
225     for out_file in @PgmStdoutFile ; do
226         if sed "s/\\r\$//" $TmpPrefix/runtest$$.1 | cmp -s \$out_file - ; then
227             hit='YES'
228         fi
229     done
230     if [ \$hit = 'NO' ] ; then
231         echo $ToRun @PgmArgs \\< $PgmStdinFile
232         echo expected stdout not matched by reality
233         orig_file="$PgmStdoutFile[0]";
234         [ ! -f \$orig_file ] && orig_file="/dev/null"
235         ${CONTEXT_DIFF} \$orig_file $TmpPrefix/runtest$$.1
236         myexit=\$?
237         diffsShown=1
238     fi
239     if [ $SaveStdout = 1 ] && 
240        [ $PgmStdoutFile[0] != $DefaultStdoutFile ] && [ -s $TmpPrefix/runtest$$.1 ]; then
241         echo Saving away stdout output in $PgmStdoutFile[0] ...
242         if [ -f $PgmStdoutFile[0] ]; then
243              rm -f $PgmStdoutFile[0].bak
244              cp $PgmStdoutFile[0] $PgmStdoutFile[0].bak
245         fi;
246         cp $TmpPrefix/runtest$$.1 $PgmStdoutFile[0]
247     fi
248 fi
249
250 hit='NO'
251 for out_file in @PgmStderrFile ; do
252     if sed "s/\\r\$//" $TmpPrefix/runtest$$.2 | cmp -s \$out_file - ; then
253         hit='YES'
254     fi
255 done
256 if [ \$hit = 'NO' ] ; then
257     echo $ToRun @PgmArgs \\< $PgmStdinFile
258     echo expected stderr not matched by reality
259     orig_file="$PgmStderrFile[0]"
260     [ ! -f \$orig_file ] && orig_file="/dev/null"
261     ${CONTEXT_DIFF} \$orig_file $TmpPrefix/runtest$$.2
262     myexit=\$?
263     diffsShown=1
264 fi
265 if [ $SaveStderr = 1 ] &&
266    [ $PgmStderrFile[0] != $DefaultStderrFile ] && [ -s $TmpPrefix/runtest$$.2 ]; then
267         echo Saving away stderr output in $PgmStderrFile[0] ...
268         if [ -f $PgmStderrFile[0] ]; then
269            rm -f $PgmStderrFile[0].bak
270            cp $PgmStderrFile[0] $PgmStderrFile[0].bak
271         fi;
272         cp $TmpPrefix/runtest$$.2 $PgmStderrFile[0]
273 fi
274
275 ${RM} core $ToRunOrig.spix $DefaultStdoutFile $DefaultStderrFile $TmpPrefix/runtest$$.1 $TmpPrefix/runtest$$.2 $TmpPrefix/runtest$$.3
276 exit \$myexit
277 EOSCRIPT
278
279 # bung script into a file
280 open(SCR, "> $ScriptFile") || die "Failed opening script file $ScriptFile!\n";
281 print SCR $Script;
282 close(SCR) || die "Failed closing script file!\n";
283 chmod 0755, $ScriptFile;
284
285 print STDERR $Script if $Verbose;
286
287 &run_something($ScriptFile);
288
289 if ( $SysSpecificTiming eq '' ) {
290     unlink $StatsFile;
291     unlink $ScriptFile;
292     exit 0;
293 }
294
295 &process_stats_file();
296 &process_cachegrind_files() if $Cachegrind eq 'yes';
297
298 # print out what we found
299 print STDERR "<<$SysSpecificTiming: ";
300 if ( $Cachegrind ne 'yes') {
301         print STDERR "$BytesAlloc bytes, $GCs GCs, $AvgResidency/$MaxResidency avg/max bytes residency ($ResidencySamples samples), $GCWork bytes GC work, ${TotMem}M in use, $InitTime INIT ($InitElapsed elapsed), $MutTime MUT ($MutElapsed elapsed), $GcTime GC ($GcElapsed elapsed)";
302 } else {
303         print STDERR "$BytesAlloc bytes, $GCs GCs, $AvgResidency/$MaxResidency avg/max bytes residency ($ResidencySamples samples), $GCWork bytes GC work, ${TotMem}M in use, $InitTime INIT ($InitElapsed elapsed), $MutTime MUT ($MutElapsed elapsed), $GcTime GC ($GcElapsed elapsed), $TotInstrs instructions, $TotReads memory reads, $TotWrites memory writes, $TotMisses L2 cache misses";
304 };
305 print STDERR " :$SysSpecificTiming>>\n";
306
307 # OK, party over
308 unlink $StatsFile;
309 unlink $ScriptFile;
310 exit 0;
311
312 sub grab_arg_arg {
313     local($option, $rest_of_arg) = @_;
314     
315     if ($rest_of_arg ne "") {
316         return($rest_of_arg);
317     } elsif ($#ARGV >= 0) {
318         local($temp) = $ARGV[0]; shift(@ARGV); 
319         return($temp);
320     } else {
321         print STDERR "$Pgm: no argument following $option option\n";
322         $Status++;
323     }
324 }
325
326 sub run_something {
327     local($str_to_do) = @_;
328
329 #   print STDERR "$str_to_do\n" if $Verbose;
330
331     local($return_val) = 0;
332     system($str_to_do);
333     $return_val = $?;
334
335     if ($return_val != 0) {
336 #ToDo: this return-value mangling is wrong
337 #       local($die_msg) = "$Pgm: execution of the $tidy_name had trouble";
338 #       $die_msg .= " (program not found)" if $return_val == 255;
339 #       $die_msg .= " ($!)" if $Verbose && $! != 0;
340 #       $die_msg .= "\n";
341         unlink $ScriptFile;
342         unlink $StatsFile;
343
344         exit (($return_val == 0) ? 0 : 1);
345     }
346 }
347
348 sub process_stats_file {
349
350     # OK, process system-specific stats file
351     if ( $SysSpecificTiming =~ /^ghc/ ) {
352
353         #NB: nearly the same as in GHC driver's -ghc-timing stuff
354
355         open(STATS, $StatsFile) || die "Failed when opening $StatsFile\n";
356
357         local($max_live)    = 0; 
358         local($tot_live)    = 0; # for calculating residency stuff
359         local($tot_samples) = 0;
360
361         $GCWork = 0;
362         while (<STATS>) {
363             if (! /Gen:\s+0/ && /^\s*\d+\s+\d+\s+(\d+)\s+\d+\.\d+/ ) {
364                 $max_live = $1 if $max_live < $1;
365                 $tot_live += $1;
366                 $tot_samples += 1;
367             }
368
369             $BytesAlloc = $1 if /^\s*([0-9,]+) bytes allocated in the heap/;
370             $GCWork += $1    if /^\s*([0-9,]+) bytes copied during GC/;
371
372 #           if ( /^\s*([0-9,]+) bytes maximum residency .* (\d+) sample/ ) {
373 #               $MaxResidency = $1; $ResidencySamples = $2;
374 #           }
375
376             $GCs = $1 if /^\s*([0-9,]+) collections? in generation 0/;
377
378             if ( /^\s+([0-9]+)\s+Mb total memory/ ) {
379                 $TotMem = $1;
380             }
381
382             if ( /^\s*INIT\s+time\s*(-*\d+\.\d\d)s\s*\(\s*(-*\d+\.\d\d)s elapsed\)/ ) {
383                 $InitTime = $1; $InitElapsed = $2;
384             } elsif ( /^\s*MUT\s+time\s*(-*\d+\.\d\d)s\s*\(\s*(-*\d+\.\d\d)s elapsed\)/ ) {
385                 $MutTime = $1; $MutElapsed = $2;
386             } elsif ( /^\s*GC\s+time\s*(-*\d+\.\d\d)s\s*\(\s*(-*\d+\.\d\d)s elapsed\)/ ) {
387                 $GcTime = $1; $GcElapsed = $2;
388             }
389         }
390         close(STATS) || die "Failed when closing $StatsFile\n";
391         if ( $tot_samples > 0 ) {
392             $ResidencySamples = $tot_samples;
393             $MaxResidency = $max_live;
394             $AvgResidency = int ($tot_live / $tot_samples) ;
395         }
396
397     } elsif ( $SysSpecificTiming eq 'hbc' ) {
398
399         open(STATS, $StatsFile) || die "Failed when opening $StatsFile\n";
400         while (<STATS>) {
401             $BytesAlloc = $1 if /^\s*([0-9]+) bytes allocated from the heap/;
402
403             $GCs = $1 if /^\s*([0-9]+) GCs?,$/;
404
405             if ( /^\s*(\d+\.\d\d) \((\d+\.\d)\) seconds total time,$/ ) {
406                 $MutTime = $1; $MutElapsed = $2; # will fix up later
407
408                 $InitTime = 0; $InitElapsed = 0; # hbc doesn't report these
409
410             } elsif ( /^\s*(\d+\.\d\d) \((\d+\.\d)\) seconds GC time/ ) {
411                 $GcTime = $1; $GcElapsed = $2;
412
413                 # fix up mutator time now
414                 $MutTime    = sprintf("%.2f", ($MutTime    - $GcTime));
415                 $MutElapsed = sprintf("%.1f", ($MutElapsed - $GcElapsed));
416             }
417         }
418         close(STATS) || die "Failed when closing $StatsFile\n";
419     }
420
421     # warn about what we didn't find
422     print STDERR "Warning: BytesAlloc not found in stats file\n" unless defined($BytesAlloc);
423     print STDERR "Warning: GCs not found in stats file\n" unless defined($GCs);
424     print STDERR "Warning: InitTime not found in stats file\n" unless defined($InitTime);
425     print STDERR "Warning: InitElapsed not found in stats file\n" unless defined($InitElapsed);
426     print STDERR "Warning: MutTime not found in stats file\n" unless defined($MutTime);
427     print STDERR "Warning: MutElapsed not found in stats file\n" unless defined($MutElapsed);
428     print STDERR "Warning: GcTime inot found in stats file\n" unless defined($GcTime);
429     print STDERR "Warning: GcElapsed not found in stats file\n" unless defined($GcElapsed);
430     print STDERR "Warning: total memory not found in stats file\n" unless defined($TotMem);
431     print STDERR "Warning: GC work not found in stats file\n" unless defined($GCWork);
432
433     # things we didn't necessarily expect to find
434     $MaxResidency     = 0 unless defined($MaxResidency);
435     $AvgResidency     = 0 unless defined($AvgResidency);
436     $ResidencySamples = 0 unless defined($ResidencySamples);
437
438     # a bit of tidying
439     $BytesAlloc =~ s/,//g;
440     $GCWork =~ s/,//g;
441     $MaxResidency =~ s/,//g;
442     $GCs =~ s/,//g;
443     $InitTime =~ s/,//g;
444     $InitElapsed =~ s/,//g;
445     $MutTime =~ s/,//g;
446     $MutElapsed =~ s/,//g;
447     $GcTime =~ s/,//g;
448     $GcElapsed =~ s/,//g;
449 }
450
451 sub process_cachegrind_files {
452
453     open(STATS, "< $CachegrindStats") || die("Can't open $CachegrindStats\n");
454
455     while (<STATS>) {
456         /^==\d+==\s+I\s+refs:\s+([0-9,]*)/ && do {
457            $TotInstrs = $1;
458            $TotInstrs =~ s/,//g;
459         };
460
461         /^==\d+==\s+D\s+refs:\s+[0-9,]+\s+\(([0-9,]+)\s+rd\s+\+\s+([0-9,]+)\s+wr/ && do {
462            $TotReads  = $1;
463            $TotWrites = $2;
464            $TotReads  =~ s/,//g;
465            $TotWrites =~ s/,//g;
466         };
467
468         /^==\d+==\s+L2d\s+misses:\s+([0-9,]+)/ && do {
469            $TotMisses = $1;
470            $TotMisses =~ s/,//g;
471         };
472     }
473     close(STATS);
474 }
475