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