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