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