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