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