[project @ 2000-09-05 10:16:40 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 $Heimdall = 0;
66 $HeimdallPrefix = '';
67 $HeimdallStats = "heimdall.summary";
68 $StatsFile = "$TmpPrefix/stats$$";
69 $CacheProfStats = "cacheprof.out.summary";
70 $SysSpecificTiming = '';
71 $CacheProf = 'no';
72
73 die "$Pgm: program to run not given as first argument\n" if $#ARGV < 0;
74 $ToRun = $ARGV[0]; shift(@ARGV);
75 # avoid picking up same-named thing from somewhere else on $PATH...
76 $ToRun = "./$ToRun" if $ToRun !~ /^\//;
77
78 arg: while ($_ = $ARGV[0]) {
79     shift(@ARGV);
80     
81     /^--$/      && do { # let anything past after --
82                         push(@PgmArgs, @ARGV);
83                         last arg; };
84
85     /^-v$/             && do { $Verbose = 1; next arg; };
86     /^-accept-output-stderr$/ && do { $SaveStderr = 1; next arg; };
87     /^-accept-output-stdout$/ && do { $SaveStdout = 1; next arg; };
88     /^-accept-output$/        && do { $SaveStdout = 1; $SaveStderr = 1; next arg; };
89
90     /^-O(.*)/   && do { push(@PgmArgs, &grab_arg_arg('-O',$1)); next arg; };
91     /^-i(.*)/   && do { $PgmStdinFile = &grab_arg_arg('-i',$1);
92                         $Status++,
93                         print STDERR "$Pgm: bogus -i input file: $PgmStdinFile\n"
94                             if $PgmStdinFile !~ /^\/dev\/.*$/ && ! -f $PgmStdinFile;
95                         next arg; };
96     /^-fail/    && do { $PgmFail=1; next arg; };
97     /^-x(.*)/   && do { $PgmExitStatus = &grab_arg_arg('-x',$1);
98                         $Status++ ,
99                         print STDERR "$Pgm: bogus -x expected exit status: $PgmExitStatus\n"
100                             if $PgmExitStatus !~ /^\d+$/;
101                         next arg; };
102     /^-o1(.*)/  && do { $out_file = &grab_arg_arg('-o1',$1);
103                         push(@PgmStdoutFile, $out_file);
104                         next arg; };
105     /^-o2(.*)/  && do { $out_file = &grab_arg_arg('-o2',$1);
106                         push(@PgmStderrFile, $out_file);
107                         next arg; };
108     /^-prescript(.*)/  && do { $PreScript = &grab_arg_arg('-prescript',$1);
109                                 next arg; };
110     /^-postscript(.*)/ && do { $PostScript = &grab_arg_arg('-postscript',$1);
111                                 next arg; };
112     /^-script/ && do { print STDERR "$Pgm: -script argument is obsolete;\nUse -prescript and -postscript instead.\n";
113                     $Status++;
114                     next arg; };
115     /^-(ghc|hbc)-timing$/ && do { $SysSpecificTiming = $1;
116                                   next arg; };
117     /^-cacheprof$/ && do { $SysSpecificTiming = 'ghc-instrs';
118                            $CacheProf = 'yes'; 
119                            next arg };
120     /^-heimdall$/ && do { $HeimdallPrefix = 'heimdall_cp ';  # must have trailing space!
121                           $SysSpecificTiming = 'ghc-instrs';
122                           $Heimdall = 1;
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 } else {
178     $PreScriptLines = '';
179 }
180
181 if ($PostScript ne '') {
182     local($to_do);
183     $PostScriptLines = `cat $PostScript`;
184     $* = 1;
185     $PostScriptLines =~ s#\$o1#$TmpPrefix/runtest$$.1#g;
186     $PostScriptLines =~ s#\$o2#$TmpPrefix/runtest$$.2#g;
187 } else {
188     $PostScriptLines = '';
189 }
190
191 # OK, so we're gonna do the normal thing...
192
193 $Script = <<EOSCRIPT;
194 #! /bin/sh
195 myexit=0
196 diffsShown=0
197 rm -f $DefaultStdoutFile $DefaultStderrFile
198 cat /dev/null > $DefaultStdoutFile
199 cat /dev/null > $DefaultStderrFile
200 $PreScriptLines
201 $SpixifyLine1
202 $TimeCmd /bin/sh -c \'$HeimdallPrefix$ToRun $TimingMagic @PgmArgs < $PgmStdinFile 1> $TmpPrefix/runtest$$.1 2> $TmpPrefix/runtest$$.2 3> $TmpPrefix/runtest$$.3\'
203 progexit=\$?
204 if [ \$progexit -eq 0 ] && [ $PgmFail -ne 0 ]; then
205     echo $ToRun @PgmArgs \\< $PgmStdinFile
206     echo "****" expected a failure, but was successful
207     myexit=1
208 fi
209 if [ \$progexit -ne $PgmExitStatus ] && [ $PgmFail -eq 0 ]; then
210     echo $ToRun @PgmArgs \\< $PgmStdinFile
211     echo "****" expected exit status $PgmExitStatus not seen \\; got \$progexit
212     myexit=1
213 else
214     $PostScriptLines
215     hit='NO'
216     for out_file in @PgmStdoutFile ; do
217         if cmp -s \$out_file $TmpPrefix/runtest$$.1 ; then
218             hit='YES'
219         fi
220     done
221     if [ \$hit = 'NO' ] ; then
222         echo $ToRun @PgmArgs \\< $PgmStdinFile
223         echo expected stdout not matched by reality
224         orig_file="$PgmStdoutFile[0]";
225         [ ! -f \$orig_file ] && orig_file="/dev/null"
226         ${CONTEXT_DIFF} \$orig_file $TmpPrefix/runtest$$.1
227         myexit=\$?
228         diffsShown=1
229     fi
230     if [ $SaveStdout = 1 ] && 
231        [ $PgmStdoutFile[0] != $DefaultStdoutFile ] && [ -s $TmpPrefix/runtest$$.1 ]; then
232         echo Saving away stdout output in $PgmStdoutFile[0] ...
233         if [ -f $PgmStdoutFile[0] ]; then
234              rm -f $PgmStdoutFile[0].bak
235              cp $PgmStdoutFile[0] $PgmStdoutFile[0].bak
236         fi;
237         cp $TmpPrefix/runtest$$.1 $PgmStdoutFile[0]
238     fi
239 fi
240 egrep -v '^ld\.so:.*has older revision than expected' < $TmpPrefix/runtest$$.2 > $TmpPrefix/runtest$$.2b
241 mv -f $TmpPrefix/runtest$$.2b $TmpPrefix/runtest$$.2
242 egrep '^=== HEIMDALL: ' < $TmpPrefix/runtest$$.2 > $HeimdallStats
243 egrep -v '^=== HEIMDALL: ' < $TmpPrefix/runtest$$.2 > $TmpPrefix/runtest$$.2b
244 mv -f $TmpPrefix/runtest$$.2b $TmpPrefix/runtest$$.2
245
246 hit='NO'
247 for out_file in @PgmStderrFile ; do
248     if cmp -s \$out_file $TmpPrefix/runtest$$.2 ; then
249         hit='YES'
250     fi
251 done
252 if [ \$hit = 'NO' ] ; then
253     echo $ToRun @PgmArgs \\< $PgmStdinFile
254     echo expected stderr not matched by reality
255     orig_file="$PgmStderrFile[0]"
256     [ ! -f \$orig_file ] && orig_file="/dev/null"
257     ${CONTEXT_DIFF} \$orig_file $TmpPrefix/runtest$$.2
258     myexit=\$?
259     diffsShown=1
260 fi
261 if [ $SaveStderr = 1 ] &&
262    [ $PgmStderrFile[0] != $DefaultStderrFile ] && [ -s $TmpPrefix/runtest$$.2 ]; then
263         echo Saving away stderr output in $PgmStderrFile[0] ...
264         if [ -f $PgmStderrFile[0] ]; then
265            rm -f $PgmStderrFile[0].bak
266            cp $PgmStderrFile[0] $PgmStderrFile[0].bak
267         fi;
268         cp $TmpPrefix/runtest$$.2 $PgmStderrFile[0]
269 fi
270
271 ${RM} core $ToRunOrig.spix $DefaultStdoutFile $DefaultStderrFile $TmpPrefix/runtest$$.1 $TmpPrefix/runtest$$.2 $TmpPrefix/runtest$$.3
272 exit \$myexit
273 EOSCRIPT
274
275 # bung script into a file
276 open(SCR, "> $ScriptFile") || die "Failed opening script file $ScriptFile!\n";
277 print SCR $Script;
278 close(SCR) || die "Failed closing script file!\n";
279 chmod 0755, $ScriptFile;
280
281 print STDERR $Script if $Verbose;
282
283 &run_something($ScriptFile);
284
285 if ( $SysSpecificTiming eq '' ) {
286     unlink $StatsFile;
287     unlink $ScriptFile;
288     exit 0;
289 }
290
291 &process_stats_file();
292 &process_cacheprof_files() if $CacheProf eq 'yes';
293 &process_heimdall_file() if $Heimdall;
294
295 # print out what we found
296 print STDERR "<<$SysSpecificTiming: ";
297 if ( $CacheProf ne 'yes' && !$Heimdall) {
298         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)";
299 } else {
300         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";
301 };
302 print STDERR " :$SysSpecificTiming>>\n";
303
304 # OK, party over
305 unlink $StatsFile;
306 unlink $ScriptFile;
307 exit 0;
308
309 sub grab_arg_arg {
310     local($option, $rest_of_arg) = @_;
311     
312     if ($rest_of_arg) {
313         return($rest_of_arg);
314     } elsif ($#ARGV >= 0) {
315         local($temp) = $ARGV[0]; shift(@ARGV); 
316         return($temp);
317     } else {
318         print STDERR "$Pgm: no argument following $option option\n";
319         $Status++;
320     }
321 }
322
323 sub run_something {
324     local($str_to_do) = @_;
325
326 #   print STDERR "$str_to_do\n" if $Verbose;
327
328     local($return_val) = 0;
329     system($str_to_do);
330     $return_val = $?;
331
332     if ($return_val != 0) {
333 #ToDo: this return-value mangling is wrong
334 #       local($die_msg) = "$Pgm: execution of the $tidy_name had trouble";
335 #       $die_msg .= " (program not found)" if $return_val == 255;
336 #       $die_msg .= " ($!)" if $Verbose && $! != 0;
337 #       $die_msg .= "\n";
338         unlink $ScriptFile;
339         unlink $StatsFile;
340
341         exit (($return_val == 0) ? 0 : 1);
342     }
343 }
344
345 sub process_stats_file {
346
347     # OK, process system-specific stats file
348     if ( $SysSpecificTiming =~ /^ghc/ ) {
349
350         #NB: nearly the same as in GHC driver's -ghc-timing stuff
351
352         open(STATS, $StatsFile) || die "Failed when opening $StatsFile\n";
353
354         local($max_live)    = 0; 
355         local($tot_live)    = 0; # for calculating residency stuff
356         local($tot_samples) = 0;
357
358         while (<STATS>) {
359             if (! /Gen:\s+0/ && /^\s*\d+\s+\d+\s+(\d+)\s+\d+\.\d+/ ) {
360                 $max_live = $1 if $max_live < $1;
361                 $tot_live += $1;
362                 $tot_samples += 1;
363             }
364
365             $BytesAlloc = $1 if /^\s*([0-9,]+) bytes allocated in the heap/;
366             $GCWork = $1     if /^\s*([0-9,]+) bytes copied during GC/;
367
368 #           if ( /^\s*([0-9,]+) bytes maximum residency .* (\d+) sample/ ) {
369 #               $MaxResidency = $1; $ResidencySamples = $2;
370 #           }
371
372             $GCs = $1 if /^\s*([0-9,]+) collections? in generation 0/;
373
374             if ( /^\s+([0-9]+)\s+Mb total memory/ ) {
375                 $TotMem = $1;
376             }
377
378             if ( /^\s*INIT\s+time\s*(-*\d+\.\d\d)s\s*\(\s*(-*\d+\.\d\d)s elapsed\)/ ) {
379                 $InitTime = $1; $InitElapsed = $2;
380             } elsif ( /^\s*MUT\s+time\s*(-*\d+\.\d\d)s\s*\(\s*(-*\d+\.\d\d)s elapsed\)/ ) {
381                 $MutTime = $1; $MutElapsed = $2;
382             } elsif ( /^\s*GC\s+time\s*(-*\d+\.\d\d)s\s*\(\s*(-*\d+\.\d\d)s elapsed\)/ ) {
383                 $GcTime = $1; $GcElapsed = $2;
384             }
385         }
386         close(STATS) || die "Failed when closing $StatsFile\n";
387         if ( $tot_samples > 0 ) {
388             $ResidencySamples = $tot_samples;
389             $MaxResidency = $max_live;
390             $AvgResidency = int ($tot_live / $tot_samples) ;
391         }
392
393     } elsif ( $SysSpecificTiming eq 'hbc' ) {
394
395         open(STATS, $StatsFile) || die "Failed when opening $StatsFile\n";
396         while (<STATS>) {
397             $BytesAlloc = $1 if /^\s*([0-9]+) bytes allocated from the heap/;
398
399             $GCs = $1 if /^\s*([0-9]+) GCs?,$/;
400
401             if ( /^\s*(\d+\.\d\d) \((\d+\.\d)\) seconds total time,$/ ) {
402                 $MutTime = $1; $MutElapsed = $2; # will fix up later
403
404                 $InitTime = 0; $InitElapsed = 0; # hbc doesn't report these
405
406             } elsif ( /^\s*(\d+\.\d\d) \((\d+\.\d)\) seconds GC time/ ) {
407                 $GcTime = $1; $GcElapsed = $2;
408
409                 # fix up mutator time now
410                 $MutTime    = sprintf("%.2f", ($MutTime    - $GcTime));
411                 $MutElapsed = sprintf("%.1f", ($MutElapsed - $GcElapsed));
412             }
413         }
414         close(STATS) || die "Failed when closing $StatsFile\n";
415     }
416
417     # warn about what we didn't find
418     print STDERR "Warning: BytesAlloc not found in stats file\n" unless defined($BytesAlloc);
419     print STDERR "Warning: GCs not found in stats file\n" unless defined($GCs);
420     print STDERR "Warning: InitTime not found in stats file\n" unless defined($InitTime);
421     print STDERR "Warning: InitElapsed not found in stats file\n" unless defined($InitElapsed);
422     print STDERR "Warning: MutTime not found in stats file\n" unless defined($MutTime);
423     print STDERR "Warning: MutElapsed not found in stats file\n" unless defined($MutElapsed);
424     print STDERR "Warning: GcTime inot found in stats file\n" unless defined($GcTime);
425     print STDERR "Warning: GcElapsed not found in stats file\n" unless defined($GcElapsed);
426     print STDERR "Warning: total memory not found in stats file\n" unless defined($TotMem);
427     print STDERR "Warning: GC work not found in stats file\n" unless defined($GCWork);
428
429     # things we didn't necessarily expect to find
430     $MaxResidency     = 0 unless defined($MaxResidency);
431     $AvgResidency     = 0 unless defined($AvgResidency);
432     $ResidencySamples = 0 unless defined($ResidencySamples);
433
434     # a bit of tidying
435     $BytesAlloc =~ s/,//g;
436     $GCWork =~ s/,//g;
437     $MaxResidency =~ s/,//g;
438     $GCs =~ s/,//g;
439     $InitTime =~ s/,//g;
440     $InitElapsed =~ s/,//g;
441     $MutTime =~ s/,//g;
442     $MutElapsed =~ s/,//g;
443     $GcTime =~ s/,//g;
444     $GcElapsed =~ s/,//g;
445 }
446
447 sub process_cacheprof_files {
448
449     open(STATS, "< $CacheProfStats") || die("Can't open $CacheProfStats\n");
450
451     # the format of the info in this file is:
452     #    OTHER(intrs,reads,writes,read-misses,write-misses)
453     # where read-misses and write-misses will both be zero if we're
454     # just counting instructions.
455     while (<STATS>) {
456        /OTHER\(\s*([0-9]+),\s*([0-9]+),\s*([0-9]+),\s*([0-9]+),\s*([0-9]+)\)/ && do {
457            $TotInstrs = $1;
458            $TotReads  = $2;
459            $TotWrites = $3;
460       }
461   }
462   close(STATS);
463 }
464
465 sub process_heimdall_file {
466
467     open(STATS, "< $HeimdallStats") || die("Can't open $HeimdallStats\n");
468
469     # instruction counts from Julian Seward's HEIMDALL:
470     #
471     # === HEIMDALL: instruction counts: 815000 instrs, 230040 reads, 138692 writes
472     while (<STATS>) {
473        /^=== HEIMDALL: instruction counts: ([0-9]+) instrs, ([0-9]+) reads, ([0-9]+) writes/
474            && do {
475            $TotInstrs = $1;
476            $TotReads  = $2;
477            $TotWrites = $3;
478       }
479   }
480   close(STATS);
481 }
482