Make timeouts based on CPU time.
[pintos-anon] / src / utils / pintos
1 #! /usr/bin/perl -w
2
3 use strict;
4 use POSIX;
5 use Fcntl;
6 use File::Temp 'tempfile';
7 use Getopt::Long qw(:config bundling);
8
9 # Command-line options.
10 our ($start_time) = time ();
11 our ($sim);                     # Simulator: bochs, qemu, or gsx.
12 our ($debug) = "none";          # Debugger: none, monitor, or gdb.
13 our ($mem) = 4;                 # Physical RAM in MB.
14 our ($serial_out) = 1;          # Send output to serial port?
15 our ($vga);                     # VGA output: window, terminal, or none.
16 our ($jitter);                  # Seed for random timer interrupts, if set.
17 our ($realtime);                # Synchronize timer interrupts with real time?
18 our ($timeout);                 # Maximum runtime in seconds, if set.
19 our (@puts);                    # Files to copy into the VM.
20 our (@gets);                    # Files to copy out of the VM.
21 our ($as_ref);                  # Reference to last addition to @gets or @puts.
22 our (@kernel_args);             # Arguments to pass to kernel.
23 our (%disks) = (OS => {DEF_FN => 'os.dsk'},             # Disks to give VM.
24                 FS => {DEF_FN => 'fs.dsk'},
25                 SCRATCH => {DEF_FN => 'scratch.dsk'},
26                 SWAP => {DEF_FN => 'swap.dsk'});
27 our (@disks_by_iface) = @disks{qw (OS FS SCRATCH SWAP)};
28
29 parse_command_line ();
30 find_disks ();
31 prepare_scratch_disk ();
32 prepare_arguments ();
33 run_vm ();
34 finish_scratch_disk ();
35
36 exit 0;
37 \f
38 # Parses the command line.
39 sub parse_command_line {
40     usage (0) if @ARGV == 0 || (@ARGV == 1 && $ARGV[0] eq '--help');
41     
42     @kernel_args = @ARGV;
43     if (grep ($_ eq '--', @kernel_args)) {
44         @ARGV = ();
45         while ((my $arg = shift (@kernel_args)) ne '--') {
46             push (@ARGV, $arg);
47         }
48         GetOptions ("sim=s" => sub { set_sim (@_) },
49                     "bochs" => sub { set_sim ("bochs") },
50                     "qemu" => sub { set_sim ("qemu") },
51                     "gsx" => sub { set_sim ("gsx") },
52
53                     "debug=s" => sub { set_debug (@_) },
54                     "no-debug" => sub { set_debug ("none") },
55                     "monitor" => sub { set_debug ("monitor") },
56                     "gdb" => sub { set_debug ("gdb") },
57
58                     "m|memory=i" => \$mem,
59                     "j|jitter=i" => sub { set_jitter (@_) },
60                     "r|realtime" => sub { set_realtime () },
61                     "T|timeout=i" => \$timeout,
62
63                     "v|no-vga" => sub { set_vga ('none'); },
64                     "s|no-serial" => sub { $serial_out = 0; },
65                     "t|terminal" => sub { set_vga ('terminal'); },
66
67                     "p|put-file=s" => sub { add_file (\@puts, $_[1]); },
68                     "g|get-file=s" => sub { add_file (\@gets, $_[1]); },
69                     "a|as=s" => sub { set_as ($_[1]); },
70
71                     "h|help" => sub { usage (0); },
72
73                     "os-disk=s" => \$disks{OS}{FILENAME},
74                     "fs-disk=s" => \$disks{FS}{FILENAME},
75                     "scratch-disk=s" => \$disks{SCRATCH}{FILENAME},
76                     "swap-disk=s" => \$disks{SWAP}{FILENAME},
77
78                     "0|disk-0|hda=s" => \$disks_by_iface[0]{FILENAME},
79                     "1|disk-1|hdb=s" => \$disks_by_iface[1]{FILENAME},
80                     "2|disk-2|hdc=s" => \$disks_by_iface[2]{FILENAME},
81                     "3|disk-3|hdd=s" => \$disks_by_iface[3]{FILENAME})
82           or exit 1;
83     }
84
85     $sim = "bochs" if !defined $sim;
86     $debug = "none" if !defined $debug;
87     $vga = "window" if !defined $vga;
88 }
89
90 # usage($exitcode).
91 # Prints a usage message and exits with $exitcode.
92 sub usage {
93     my ($exitcode) = @_;
94     $exitcode = 1 unless defined $exitcode;
95     print <<'EOF';
96 pintos, a utility for running Pintos in a simulator
97 Usage: pintos [OPTION...] -- [ARGUMENT...]
98 where each OPTION is one of the following options
99   and each ARGUMENT is passed to Pintos kernel verbatim.
100 Simulator selection:
101   --bochs                  (default) Use Bochs as simulator
102   --qemu                   Use qemu as simulator
103   --gsx                    Use VMware GSX Server 3.x as simulator
104 Debugger selection:
105   --no-debug               (default) No debugger
106   --monitor                Debug with simulator's monitor
107   --gdb                    Debug with gdb
108 Display options: (default is both VGA and serial)
109   -v, --no-vga             No VGA display
110   -s, --no-serial          No serial output
111   -t, --terminal           Display VGA in terminal (Bochs only)
112 Timing options: (Bochs only)
113   -j SEED                  Randomize timer interrupts
114   -r, --realtime           Use realistic, not reproducible, timings
115   -T, --timeout=N          Kill Pintos after N seconds CPU time or N*load_avg
116                            seconds wall-clock time (whichever comes first)
117 Configuration options:
118   -m, --mem=N              Give Pintos N MB physical RAM (default: 4)
119 File system commands (for `run' command):
120   -p, --put-file=HOSTFN    Copy HOSTFN into VM, by default under same name
121   -g, --get-file=GUESTFN   Copy GUESTFN out of VM, by default under same name
122   -a, --as=FILENAME        Specifies guest (for -p) or host (for -g) file name
123 Disk options: (name an existing FILE or specify SIZE in MB for a temp disk)
124   --os-disk=FILE           Set OS disk file (default: os.dsk)
125   --fs-disk=FILE|SIZE      Set FS disk file (default: fs.dsk)
126   --scratch-disk=FILE|SIZE Set scratch disk (default: scratch.dsk)
127   --swap-disk=FILE|SIZE    Set swap disk file (default: swap.dsk)
128 Other options:
129   -h, --help               Display this help message.
130 EOF
131     exit $exitcode;
132 }
133
134 # Sets the simulator.
135 sub set_sim {
136     my ($new_sim) = @_;
137     die "--$new_sim conflicts with --$sim\n"
138         if defined ($sim) && $sim ne $new_sim;
139     $sim = $new_sim;
140 }
141
142 # Sets the debugger.
143 sub set_debug {
144     my ($new_debug) = @_;
145     die "--$new_debug conflicts with --$debug\n"
146         if $debug ne 'none' && $new_debug ne 'none' && $debug ne $new_debug;
147     $debug = $new_debug;
148 }
149
150 # Sets VGA output destination.
151 sub set_vga {
152     my ($new_vga) = @_;
153     if (defined ($vga) && $vga ne $new_vga) {
154         print "warning: conflicting vga display options\n";
155     }
156     $vga = $new_vga;
157 }
158
159 # Sets randomized timer interrupts.
160 sub set_jitter {
161     my ($new_jitter) = @_;
162     die "--realtime conflicts with --jitter\n" if defined $realtime;
163     die "different --jitter already defined\n"
164         if defined $jitter && $jitter != $new_jitter;
165     $jitter = $new_jitter;
166 }
167
168 # Sets real-time timer interrupts.
169 sub set_realtime {
170     die "--realtime conflicts with --jitter\n" if defined $jitter;
171     $realtime = 1;
172 }
173
174 # add_file(\@list, $file)
175 #
176 # Adds [$file] to @list, which should be @puts or @gets.
177 # Sets $as_ref to point to the added element.
178 sub add_file {
179     my ($list, $file) = @_;
180     $as_ref = [$file];
181     push (@$list, $as_ref);
182 }
183
184 # Sets the guest/host name for the previous put/get.
185 sub set_as {
186     my ($as) = @_;
187     die "-a (or --as) is only allowed after -p or -g\n" if !defined $as_ref;
188     die "Only one -a (or --as) is allowed after -p or -g\n"
189       if defined $as_ref->[1];
190     $as_ref->[1] = $as;
191 }
192 \f
193 # Locates the files used to back each of the virtual disks,
194 # and creates temporary disks.
195 sub find_disks {
196     for my $disk (values %disks) {
197         # If there's no assigned file name but the default file exists,
198         # try to assign a default file name.
199         if (!defined ($disk->{FILENAME})) {
200             for my $try_fn ($disk->{DEF_FN}, "build/" . $disk->{DEF_FN}) {
201                 $disk->{FILENAME} = $try_fn, last
202                   if -e $try_fn;
203             }
204         }
205
206         # If there's no file name, we're done.
207         next if !defined ($disk->{FILENAME});
208
209         if ($disk->{FILENAME} =~ /^\d+(\.\d+)?|\.\d+$/) {
210             # Create a temporary disk of approximately the specified
211             # size in megabytes.
212             die "OS disk can't be temporary\n" if $disk == $disks{OS};
213
214             my ($mb) = $disk->{FILENAME};
215             undef $disk->{FILENAME};
216
217             my ($cyl_size) = 512 * 16 * 63;
218             extend_disk ($disk, ceil ($mb * 2) * $cyl_size);
219         } else {
220             # The file must exist and have nonzero size.
221             -e $disk->{FILENAME} or die "$disk->{FILENAME}: stat: $!\n";
222             -s _ or die "$disk->{FILENAME}: disk has zero size\n";
223         }
224     }
225
226     # Warn about (potentially) missing disks.
227     die "Cannot find OS disk\n" if !defined $disks{OS}{FILENAME};
228     if (my ($project) = `pwd` =~ /\b(threads|userprog|vm|filesys)\b/) {
229         if ((grep ($project eq $_, qw (userprog vm filesys)))
230             && !defined ($disks{FS}{FILENAME})) {
231             print STDERR "warning: it looks like you're running the $project ";
232             print STDERR "project, but no file system disk is present\n";
233         }
234         if ($project eq 'vm' && !defined $disks{SWAP}{FILENAME}) {
235             print STDERR "warning: it looks like you're running the $project ";
236             print STDERR "project, but no swap disk is present\n";
237         }
238     }
239 }
240 \f
241 # Prepare the scratch disk for gets and puts.
242 sub prepare_scratch_disk {
243     # Copy the files to put onto the scratch disk.
244     put_scratch_file ($_->[0]) foreach @puts;
245
246     # Make sure the scratch disk is big enough to get big files.
247     extend_disk ($disks{SCRATCH}, @gets * 1024 * 1024) if @gets;
248 }
249
250 # Read "get" files from the scratch disk.
251 sub finish_scratch_disk {
252     # We need to start reading the scratch disk from the beginning again.
253     if (@gets) {
254         close ($disks{SCRATCH}{HANDLE});
255         undef ($disks{SCRATCH}{HANDLE});
256     }
257
258     # Read each file.
259     get_scratch_file (defined ($_->[1]) ? $_->[1] : $_->[0]) foreach @gets;
260 }
261
262 # put_scratch_file($file).
263 #
264 # Copies $file into the scratch disk.
265 sub put_scratch_file {
266     my ($put_filename) = @_;
267     my ($disk_handle, $disk_filename) = open_disk ($disks{SCRATCH});
268
269     print "Copying $put_filename into $disk_filename...\n";
270
271     # Write metadata sector, which consists of a 4-byte signature
272     # followed by the file size.
273     stat $put_filename or die "$put_filename: stat: $!\n";
274     my ($size) = -s _;
275     my ($metadata) = pack ("a4 V x504", "PUT\0", $size);
276     write_fully ($disk_handle, $disk_filename, $metadata);
277
278     # Copy file data.
279     my ($put_handle);
280     sysopen ($put_handle, $put_filename, O_RDONLY)
281       or die "$put_filename: open: $!\n";
282     copy_file ($put_handle, $put_filename, $disk_handle, $disk_filename,
283                $size);
284     close ($put_handle);
285
286     # Round up disk data to beginning of next sector.
287     write_fully ($disk_handle, $disk_filename, "\0" x (512 - $size % 512))
288       if $size % 512;
289 }
290
291 # get_scratch_file($file).
292 #
293 # Copies from the scratch disk to $file.
294 sub get_scratch_file {
295     my ($get_filename) = @_;
296     my ($disk_handle, $disk_filename) = open_disk ($disks{SCRATCH});
297
298     print "Copying $get_filename out of $disk_filename...\n";
299
300     # Read metadata sector, which has a 4-byte signature followed by
301     # the file size.
302     my ($metadata) = read_fully ($disk_handle, $disk_filename, 512);
303     my ($signature, $size) = unpack ("a4 V", $metadata);
304     die "bad signature reading scratch disk--did Pintos run correctly?\n"
305       if $signature ne "GET\0";
306
307     # Copy file data.
308     my ($get_handle);
309     sysopen ($get_handle, $get_filename, O_WRONLY | O_CREAT | O_EXCL, 0666)
310       or die "$get_filename: create: $!\n";
311     copy_file ($disk_handle, $disk_filename, $get_handle, $get_filename,
312                $size);
313     close ($get_handle);
314
315     # Skip forward in disk up to beginning of next sector.
316     read_fully ($disk_handle, $disk_filename, 512 - $size % 512)
317       if $size % 512;
318 }
319 \f
320 # Prepares the arguments to pass to the Pintos kernel,
321 # and then write them into Pintos bootloader.
322 sub prepare_arguments {
323     my (@args);
324     push (@args, shift (@kernel_args))
325       while @kernel_args && $kernel_args[0] =~ /^-/;
326     push (@args, 'put', defined $_->[1] ? $_->[1] : $_->[0]) foreach @puts;
327     push (@args, @kernel_args);
328     push (@args, 'get', $_->[0]) foreach @gets;
329     write_cmd_line ($disks{OS}, @args);
330 }
331
332 # Writes @args into the Pintos bootloader at the beginning of $disk.
333 sub write_cmd_line {
334     my ($disk, @args) = @_;
335
336     # Figure out command line to write.
337     my ($arg_cnt) = pack ("V", scalar (@args));
338     my ($args) = join ('', map ("$_\0", @args));
339     die "command line exceeds 128 bytes" if length ($args) > 128;
340     $args .= "\0" x (128 - length ($args));
341
342     # Write command line.
343     my ($handle, $filename) = open_disk_copy ($disk);
344     print "Writing command line to $filename...\n";
345     sysseek ($handle, 0x17a, 0) == 0x17a or die "$filename: seek: $!\n";
346     syswrite ($handle, "$arg_cnt$args") or die "$filename: write: $!\n";
347 }
348 \f
349 # Running simulators.
350
351 # Runs the selected simulator.
352 sub run_vm {
353     if ($sim eq 'bochs') {
354         run_bochs ();
355     } elsif ($sim eq 'qemu') {
356         run_qemu ();
357     } elsif ($sim eq 'gsx') {
358         run_gsx ();
359     } else {
360         die "unknown simulator `$sim'\n";
361     }
362 }
363
364 # Runs Bochs.
365 sub run_bochs {
366     # Select Bochs binary based on the chosen debugger.
367     my ($bin);
368     if ($debug eq 'none') {
369         $bin = 'bochs';
370     } elsif ($debug eq 'monitor') {
371         $bin = 'bochs-dbg';
372     } elsif ($debug eq 'gdb') {
373         $bin = 'bochs-gdb';
374     }
375
376     # Write bochsrc.txt configuration file.
377     open (BOCHSRC, ">", "bochsrc.txt") or die "bochsrc.txt: create: $!\n";
378     print BOCHSRC <<EOF;
379 romimage: file=\$BXSHARE/BIOS-bochs-latest, address=0xf0000
380 vgaromimage: \$BXSHARE/VGABIOS-lgpl-latest
381 boot: c
382 ips: 1000000
383 megs: $mem
384 log: bochsout.txt
385 panic: action=fatal
386 EOF
387     print BOCHSRC "clock: sync=", $realtime ? 'realtime' : 'none', "time0=0\n";
388     print_bochs_disk_line ("ata0-master", 0);
389     print_bochs_disk_line ("ata0-slave", 1);
390     if (defined ($disks_by_iface[2]{FILENAME})
391         || defined ($disks_by_iface[3]{FILENAME})) {
392         print BOCHSRC "ata1: enabled=1, ioaddr1=0x170, ",
393           "ioaddr2=0x370, irq=15\n";
394         print_bochs_disk_line ("ata1-master", 2);
395         print_bochs_disk_line ("ata1-slave", 3);
396     }
397     if ($vga ne 'terminal') {
398         print BOCHSRC "com1: enabled=1, dev=/dev/stdout\n" if $serial_out;
399         print BOCHSRC "display_library: nogui\n" if $vga eq 'none';
400     } else {
401         print BOCHSRC "display_library: term\n";
402     }
403     close (BOCHSRC);
404
405     # Compose Bochs command line.
406     my (@cmd) = ($bin, '-q');
407     push (@cmd, '-j', $jitter) if defined $jitter;
408
409     # Run Bochs.
410     print join (' ', @cmd), "\n";
411     my ($exit) = xsystem (@cmd);
412     if (WIFEXITED ($exit)) {
413         # Bochs exited normally.
414         # Ignore the exit code; Bochs normally exits with status 1,
415         # which is weird.
416     } elsif (WIFSIGNALED ($exit)) {
417         die "Bochs died with signal ", WTERMSIG ($exit), "\n";
418     } else {
419         die "Bochs died: code $exit\n";
420     }
421 }
422
423 # print_bochs_disk_line($device, $iface)
424 #
425 # If IDE interface $iface has a disk attached, prints a bochsrc.txt
426 # line for attaching it to $device.
427 sub print_bochs_disk_line {
428     my ($device, $iface) = @_;
429     my ($disk) = $disks_by_iface[$iface];
430     my ($file) = $disk->{FILENAME};
431     if (defined $file) {
432         my (%geom) = disk_geometry ($disk);
433         print BOCHSRC "$device: type=disk, path=$file, mode=flat, ";
434         print BOCHSRC "cylinders=$geom{C}, heads=$geom{H}, spt=$geom{S}, ";
435         print BOCHSRC "translation=none\n";
436     }
437 }
438
439 # Runs qemu.
440 sub run_qemu {
441     print "warning: qemu doesn't support --terminal\n"
442       if $vga eq 'terminal';
443     print "warning: qemu doesn't support jitter\n"
444       if defined $jitter;
445     my (@cmd) = ('qemu');
446     for my $iface (0...3) {
447         my ($option) = ('-hda', '-hdb', '-hdc', '-hdd')[$iface];
448         push (@cmd, $option, $disks_by_iface[$iface]{FILENAME})
449           if defined $disks_by_iface[$iface]{FILENAME};
450     }
451     push (@cmd, '-m', $mem, '-nics', '0');
452     push (@cmd, '-nographic') if $vga eq 'none';
453     push (@cmd, '-serial', 'stdio') if $serial_out && $vga ne 'none';
454     push (@cmd, '-S') if $debug eq 'monitor';
455     push (@cmd, '-s', '-S') if $debug eq 'gdb';
456     push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none';
457     run_command (@cmd);
458 }
459
460 # gsx_unsup($flag)
461 #
462 # Prints a message that $flag is unsupported by GSX Server.
463 sub gsx_unsup {
464     my ($flag) = @_;
465     print "warning: no support for $flag with VMware GSX Server\n";
466 }
467
468 # Runs VMware GSX Server.
469 sub run_gsx {
470     gsx_unsup ("--$debug") if $debug ne 'none';
471     gsx_unsup ("--no-vga") if $vga eq 'none';
472     gsx_unsup ("--terminal") if $vga eq 'terminal';
473     gsx_unsup ("--jitter") if defined $jitter;
474
475     unlink ("pintos.out");
476
477     open (VMX, ">", "pintos.vmx") or die "pintos.vmx: create: $!\n";
478     chmod 0777 & ~umask, "pintos.vmx";
479     print VMX <<EOF;
480 #! /usr/bin/vmware -G
481 config.version = 6
482 guestOS = "linux"
483 floppy0.present = FALSE
484 memsize = $mem
485
486 serial0.present = TRUE
487 serial0.fileType = "file"
488 serial0.fileName = "pintos.out"
489 EOF
490
491     for (my ($i) = 0; $i < 4; $i++) {
492         my ($disk) = $disks_by_iface[$i];
493         my ($dsk) = $disk->{FILENAME};
494         next if !defined $dsk;
495
496         my ($pln) = $dsk;
497         $pln =~ s/\.dsk//;
498         $pln .= ".pln";
499
500         my ($device) = "ide" . int ($i / 2) . ":" . ($i % 2);
501         print VMX <<EOF;
502
503 $device.present = TRUE
504 $device.deviceType = "plainDisk"
505 $device.fileName = "$pln"
506 EOF
507
508         my (%geom) = disk_geometry ($disk);
509         open (PLN, ">", $pln) or die "$pln: create: $!\n";
510         print PLN <<EOF;
511 DRIVETYPE       ide
512 #vm|VERSION     2
513 #vm|TOOLSVERSION        2
514 CYLINDERS       $geom{C}
515 HEADS           $geom{H}
516 SECTORS         $geom{S}
517 #vm|CAPACITY    $geom{CAPACITY}
518 ACCESS "$dsk" 0 $geom{CAPACITY}
519 EOF
520         close (PLN);
521     }
522     close (VMX);
523
524     my ($vmx) = getcwd () . "/pintos.vmx";
525     system ("vmware-cmd -s register $vmx >&/dev/null");
526     system ("vmware-cmd $vmx stop hard >&/dev/null");
527     system ("vmware -l -G -x -q $vmx");
528     system ("vmware-cmd $vmx stop hard >&/dev/null");
529     system ("vmware-cmd -s unregister $vmx >&/dev/null");
530 }
531 \f
532 # Disk utilities.
533
534 # open_disk($disk)
535 #
536 # Opens $disk, if it is not already open, and returns its file handle
537 # and file name.
538 sub open_disk {
539     my ($disk) = @_;
540     if (!defined ($disk->{HANDLE})) {
541         if ($disk->{FILENAME}) {
542             sysopen ($disk->{HANDLE}, $disk->{FILENAME}, O_RDWR)
543               or die "$disk->{FILENAME}: open: $!\n";
544         } else {
545             ($disk->{HANDLE}, $disk->{FILENAME}) = tempfile (UNLINK => 1,
546                                                              SUFFIX => '.dsk');
547         }
548     }
549     return ($disk->{HANDLE}, $disk->{FILENAME});
550 }
551
552 # open_disk_copy($disk)
553 #
554 # Makes a temporary copy of $disk and returns its file handle and file name.
555 sub open_disk_copy {
556     my ($disk) = @_;
557     die if !$disk->{FILENAME};
558
559     my ($orig_handle, $orig_filename) = open_disk ($disk);
560     my ($cp_handle, $cp_filename) = tempfile (UNLINK => 1, SUFFIX => '.dsk');
561     copy_file ($orig_handle, $orig_filename, $cp_handle, $cp_filename,
562                -s $orig_handle);
563     return ($disk->{HANDLE}, $disk->{FILENAME}) = ($cp_handle, $cp_filename);
564 }
565
566 # extend_disk($disk, $size)
567 #
568 # Extends $disk, if necessary, so that it is at least $size bytes
569 # long.
570 sub extend_disk {
571     my ($disk, $size) = @_;
572     my ($handle, $filename) = open_disk ($disk);
573     if (-s ($handle) < $size) {
574         sysseek ($handle, $size - 1, 0) == $size - 1
575           or die "$filename: seek: $!\n";
576         syswrite ($handle, "\0") == 1
577           or die "$filename: write: $!\n";
578     }
579 }
580
581 # disk_geometry($file)
582 #
583 # Examines $file and returns a valid IDE disk geometry for it, as a
584 # hash.
585 sub disk_geometry {
586     my ($disk) = @_;
587     my ($file) = $disk->{FILENAME};
588     my ($size) = -s $file;
589     die "$file: stat: $!\n" if !defined $size;
590     die "$file: size not a multiple of 512 bytes\n" if $size % 512;
591     my ($cyl_size) = 512 * 16 * 63;
592     my ($cylinders) = ceil ($size / $cyl_size);
593     extend_disk ($disk, $cylinders * $cyl_size) if $size % $cyl_size;
594
595     return (CAPACITY => $size / 512,
596             C => $cylinders,
597             H => 16,
598             S => 63);
599 }
600
601 # copy_file($from_handle, $from_filename, $to_handle, $to_filename, $size)
602 #
603 # Copies $size bytes from $from_handle to $to_handle.
604 # $from_filename and $to_filename are used in error messages.
605 sub copy_file {
606     my ($from_handle, $from_filename, $to_handle, $to_filename, $size) = @_;
607
608     while ($size > 0) {
609         my ($chunk_size) = 4096;
610         $chunk_size = $size if $chunk_size > $size;
611         $size -= $chunk_size;
612
613         my ($data) = read_fully ($from_handle, $from_filename, $chunk_size);
614         write_fully ($to_handle, $to_filename, $data);
615     }
616 }
617
618 # read_fully($handle, $filename, $bytes)
619 #
620 # Reads exactly $bytes bytes from $handle and returns the data read.
621 # $filename is used in error messages.
622 sub read_fully {
623     my ($handle, $filename, $bytes) = @_;
624     my ($data);
625     my ($read_bytes) = sysread ($handle, $data, $bytes);
626     die "$filename: read: $!\n" if !defined $read_bytes;
627     die "$filename: unexpected end of file\n" if $read_bytes != $bytes;
628     return $data;
629 }
630
631 # write_fully($handle, $filename, $data)
632 #
633 # Write $data to $handle.
634 # $filename is used in error messages.
635 sub write_fully {
636     my ($handle, $filename, $data) = @_;
637     my ($written_bytes) = syswrite ($handle, $data);
638     die "$filename: write: $!\n" if !defined $written_bytes;
639     die "$filename: short write\n" if $written_bytes != length $data;
640 }
641 \f
642 # Subprocess utilities.
643
644 # run_command(@args)
645 #
646 # Runs xsystem(@args).
647 # Also prints the command it's running and checks that it succeeded.
648 sub run_command {
649     print join (' ', @_), "\n";
650     die "command failed\n" if xsystem (@_);
651 }
652
653 # xsystem(@args)
654 #
655 # Creates a subprocess via exec(@args) and waits for it to complete.
656 # Relays common signals to the subprocess.
657 # If $timeout is set then the subprocess will be killed after that long.
658 sub xsystem {
659     my ($pid) = fork;
660     if (!defined ($pid)) {
661         # Fork failed.
662         die "fork: $!\n";
663     } elsif (!$pid) {
664         # Running in child process.
665         exec_setitimer (@_);
666     } else {
667         # Running in parent process.
668         local $SIG{ALRM} = sub { timeout ($pid); };
669         local $SIG{INT} = sub { relay_signal ($pid, "INT"); };
670         local $SIG{TERM} = sub { relay_signal ($pid, "TERM"); };
671         alarm ($timeout * get_load_average () + 1) if defined ($timeout);
672         waitpid ($pid, 0);
673         alarm (0);
674
675         if (WIFSIGNALED ($?) && WTERMSIG ($?) == SIGVTALRM ()) {
676             seek (STDOUT, 0, 2);
677             print "\nTIMEOUT after $timeout seconds of host CPU time\n";
678             exit 0;
679         }
680
681         return $?;
682     }
683 }
684
685 # relay_signal($pid, $signal)
686 #
687 # Relays $signal to $pid and then reinvokes it for us with the default
688 # handler.  Also cleans up temporary files.
689 sub relay_signal {
690     my ($pid, $signal) = @_;
691     kill $signal, $pid;
692     File::Temp::cleanup();
693     $SIG{$signal} = 'DEFAULT';
694     kill $signal, getpid ();
695 }
696
697 # timeout($pid)
698 #
699 # Interrupts $pid and dies with a timeout error message.
700 sub timeout {
701     my ($pid) = @_;
702     kill "INT", $pid;
703     waitpid ($pid, 0);
704     seek (STDOUT, 0, 2);
705     my ($load_avg) = `uptime` =~ /(load average:.*)$/i;
706     print "\nTIMEOUT after ", time () - $start_time,
707       " seconds of wall-clock time";
708     print  " - $load_avg" if defined $load_avg;
709     print "\n";
710     exit 0;
711 }
712
713 # Returns the system load average over the last minute.
714 # If the load average is less than 1.0 or cannot be determined, returns 1.0.
715 sub get_load_average {
716     my ($avg) = `uptime` =~ /load average:\s*([^,]+),/;
717     return $avg >= 1.0 ? $avg : 1.0;
718 }
719
720 # Calls setitimer to set a timeout, then execs what was passed to us.
721 sub exec_setitimer {
722     if (defined $timeout) {
723         if ($\16 ge 5.8.0) {
724             eval "
725               use Time::HiRes qw(setitimer ITIMER_VIRTUAL);
726               setitimer (ITIMER_VIRTUAL, $timeout, 0);
727             ";
728         } else {
729             { exec ("setitimer-helper", $timeout, @_); };
730             exit 1 if !$!{ENOENT};
731             print STDERR "warning: setitimer-helper is not installed, so ",
732               "CPU time limit will not be enforced\n";
733         }
734     }
735     exec (@_);
736     exit (1);
737 }
738
739 sub SIGVTALRM {
740     use Config;
741     my $i = 0;
742     foreach my $name (split(' ', $Config{sig_name})) {
743         return $i if $name eq 'VTALRM';
744         $i++;
745     }
746     return 0;
747 }