Implement a proper block layer with partition support.
[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');
622     push (@cmd, '-no-kqemu');
623     push (@cmd, '-hda', $disks[0]) if defined $disks[0];
624     push (@cmd, '-hdb', $disks[1]) if defined $disks[1];
625     push (@cmd, '-hdc', $disks[2]) if defined $disks[2];
626     push (@cmd, '-hdd', $disks[3]) if defined $disks[3];
627     push (@cmd, '-m', $mem);
628     push (@cmd, '-net', 'none');
629     push (@cmd, '-nographic') if $vga eq 'none';
630     push (@cmd, '-serial', 'stdio') if $serial && $vga ne 'none';
631     push (@cmd, '-S') if $debug eq 'monitor';
632     push (@cmd, '-s', '-S') if $debug eq 'gdb';
633     push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none';
634     run_command (@cmd);
635 }
636
637 # player_unsup($flag)
638 #
639 # Prints a message that $flag is unsupported by VMware Player.
640 sub player_unsup {
641     my ($flag) = @_;
642     print "warning: no support for $flag with VMware Player\n";
643 }
644
645 # Runs VMware Player.
646 sub run_player {
647     player_unsup ("--$debug") if $debug ne 'none';
648     player_unsup ("--no-vga") if $vga eq 'none';
649     player_unsup ("--terminal") if $vga eq 'terminal';
650     player_unsup ("--jitter") if defined $jitter;
651     player_unsup ("--timeout"), undef $timeout if defined $timeout;
652     player_unsup ("--kill-on-failure"), undef $kill_on_failure
653       if defined $kill_on_failure;
654
655     $mem = round_up ($mem, 4);  # Memory must be multiple of 4 MB.
656
657     open (VMX, ">", "pintos.vmx") or die "pintos.vmx: create: $!\n";
658     chmod 0777 & ~umask, "pintos.vmx";
659     print VMX <<EOF;
660 #! /usr/bin/vmware -G
661 config.version = 8
662 guestOS = "linux"
663 memsize = $mem
664 floppy0.present = FALSE
665 usb.present = FALSE
666 sound.present = FALSE
667 gui.exitAtPowerOff = TRUE
668 gui.exitOnCLIHLT = TRUE
669 gui.powerOnAtStartUp = TRUE
670 EOF
671
672     print VMX <<EOF if $serial;
673 serial0.present = TRUE
674 serial0.fileType = "pipe"
675 serial0.fileName = "pintos.socket"
676 serial0.pipe.endPoint = "client"
677 serial0.tryNoRxLoss = "TRUE"
678 EOF
679
680     for (my ($i) = 0; $i < 4; $i++) {
681         my ($dsk) = $disks[$i];
682         last if !defined $dsk;
683
684         my ($device) = "ide" . int ($i / 2) . ":" . ($i % 2);
685         my ($pln) = "$device.pln";
686         print VMX <<EOF;
687
688 $device.present = TRUE
689 $device.deviceType = "plainDisk"
690 $device.fileName = "$pln"
691 EOF
692
693         open (URANDOM, '<', '/dev/urandom') or die "/dev/urandom: open: $!\n";
694         my ($bytes);
695         sysread (URANDOM, $bytes, 4) == 4 or die "/dev/urandom: read: $!\n";
696         close (URANDOM);
697         my ($cid) = unpack ("L", $bytes);
698
699         my (%geom) = disk_geometry ($dsk);
700         open (PLN, ">", $pln) or die "$pln: create: $!\n";
701         print PLN <<EOF;
702 version=1
703 CID=$cid
704 parentCID=ffffffff
705 createType="monolithicFlat"
706
707 RW $geom{CAPACITY} FLAT "$dsk" 0
708
709 # The Disk Data Base
710 #DDB
711
712 ddb.adapterType = "ide"
713 ddb.virtualHWVersion = "4"
714 ddb.toolsVersion = "2"
715 ddb.geometry.cylinders = "$geom{C}"
716 ddb.geometry.heads = "$geom{H}"
717 ddb.geometry.sectors = "$geom{S}"
718 EOF
719         close (PLN);
720     }
721     close (VMX);
722
723     my ($squish_unix);
724     if ($serial) {
725         $squish_unix = find_in_path ("squish-unix");
726         print "warning: can't find squish-unix, so terminal input ",
727           "and output will fail\n" if !defined $squish_unix;
728     }
729
730     my ($vmx) = getcwd () . "/pintos.vmx";
731     my (@cmd) = ("vmplayer", $vmx);
732     unshift (@cmd, $squish_unix, "pintos.socket") if $squish_unix;
733     print join (' ', @cmd), "\n";
734     xsystem (@cmd);
735 }
736 \f
737 # Disk utilities.
738
739 sub extend_file {
740     my ($handle, $file_name, $size) = @_;
741     if (-s ($handle) < $size) {
742         sysseek ($handle, $size - 1, 0) == $size - 1
743           or die "$file_name: seek: $!\n";
744         syswrite ($handle, "\0") == 1
745           or die "$file_name: write: $!\n";
746     }
747 }
748
749 # disk_geometry($file)
750 #
751 # Examines $file and returns a valid IDE disk geometry for it, as a
752 # hash.
753 sub disk_geometry {
754     my ($file) = @_;
755     my ($size) = -s $file;
756     die "$file: stat: $!\n" if !defined $size;
757     die "$file: size $size not a multiple of 512 bytes\n" if $size % 512;
758     my ($cyl_size) = 512 * 16 * 63;
759     my ($cylinders) = ceil ($size / $cyl_size);
760
761     return (CAPACITY => $size / 512,
762             C => $cylinders,
763             H => 16,
764             S => 63);
765 }
766 \f
767 # Subprocess utilities.
768
769 # run_command(@args)
770 #
771 # Runs xsystem(@args).
772 # Also prints the command it's running and checks that it succeeded.
773 sub run_command {
774     print join (' ', @_), "\n";
775     die "command failed\n" if xsystem (@_);
776 }
777
778 # xsystem(@args)
779 #
780 # Creates a subprocess via exec(@args) and waits for it to complete.
781 # Relays common signals to the subprocess.
782 # If $timeout is set then the subprocess will be killed after that long.
783 sub xsystem {
784     # QEMU turns off local echo and does not restore it if killed by a signal.
785     # We compensate by restoring it ourselves.
786     my $cleanup = sub {};
787     if (isatty (0)) {
788         my $termios = POSIX::Termios->new;
789         $termios->getattr (0);
790         $cleanup = sub { $termios->setattr (0, &POSIX::TCSANOW); }
791     }
792
793     # Create pipe for filtering output.
794     pipe (my $in, my $out) or die "pipe: $!\n" if $kill_on_failure;
795
796     my ($pid) = fork;
797     if (!defined ($pid)) {
798         # Fork failed.
799         die "fork: $!\n";
800     } elsif (!$pid) {
801         # Running in child process.
802         dup2 (fileno ($out), STDOUT_FILENO) or die "dup2: $!\n"
803           if $kill_on_failure;
804         exec_setitimer (@_);
805     } else {
806         # Running in parent process.
807         close $out if $kill_on_failure;
808
809         my ($cause);
810         local $SIG{ALRM} = sub { timeout ($pid, $cause, $cleanup); };
811         local $SIG{INT} = sub { relay_signal ($pid, "INT", $cleanup); };
812         local $SIG{TERM} = sub { relay_signal ($pid, "TERM", $cleanup); };
813         alarm ($timeout * get_load_average () + 1) if defined ($timeout);
814
815         if ($kill_on_failure) {
816             # Filter output.
817             my ($buf) = "";
818             my ($boots) = 0;
819             local ($|) = 1;
820             for (;;) {
821                 if (waitpid ($pid, WNOHANG) != 0) {
822                     # Subprocess died.  Pass through any remaining data.
823                     print $buf while sysread ($in, $buf, 4096) > 0;
824                     last;
825                 }
826
827                 # Read and print out pipe data.
828                 my ($len) = length ($buf);
829                 waitpid ($pid, 0), last
830                   if sysread ($in, $buf, 4096, $len) <= 0;
831                 print substr ($buf, $len);
832
833                 # Remove full lines from $buf and scan them for keywords.
834                 while ((my $idx = index ($buf, "\n")) >= 0) {
835                     local $_ = substr ($buf, 0, $idx + 1, '');
836                     next if defined ($cause);
837                     if (/(Kernel PANIC|User process ABORT)/ ) {
838                         $cause = "\L$1\E";
839                         alarm (5);
840                     } elsif (/Pintos booting/ && ++$boots > 1) {
841                         $cause = "triple fault";
842                         alarm (5);
843                     } elsif (/FAILED/) {
844                         $cause = "test failure";
845                         alarm (5);
846                     }
847                 }
848             }
849         } else {
850             waitpid ($pid, 0);
851         }
852         alarm (0);
853         &$cleanup ();
854
855         if (WIFSIGNALED ($?) && WTERMSIG ($?) == SIGVTALRM ()) {
856             seek (STDOUT, 0, 2);
857             print "\nTIMEOUT after $timeout seconds of host CPU time\n";
858             exit 0;
859         }
860
861         return $?;
862     }
863 }
864
865 # relay_signal($pid, $signal, &$cleanup)
866 #
867 # Relays $signal to $pid and then reinvokes it for us with the default
868 # handler.  Also cleans up temporary files and invokes $cleanup.
869 sub relay_signal {
870     my ($pid, $signal, $cleanup) = @_;
871     kill $signal, $pid;
872     eval { File::Temp::cleanup() };     # Not defined in old File::Temp.
873     &$cleanup ();
874     $SIG{$signal} = 'DEFAULT';
875     kill $signal, getpid ();
876 }
877
878 # timeout($pid, $cause, &$cleanup)
879 #
880 # Interrupts $pid and dies with a timeout error message,
881 # after invoking $cleanup.
882 sub timeout {
883     my ($pid, $cause, $cleanup) = @_;
884     kill "INT", $pid;
885     waitpid ($pid, 0);
886     &$cleanup ();
887     seek (STDOUT, 0, 2);
888     if (!defined ($cause)) {
889         my ($load_avg) = `uptime` =~ /(load average:.*)$/i;
890         print "\nTIMEOUT after ", time () - $start_time,
891           " seconds of wall-clock time";
892         print  " - $load_avg" if defined $load_avg;
893         print "\n";
894     } else {
895         print "Simulation terminated due to $cause.\n";
896     }
897     exit 0;
898 }
899
900 # Returns the system load average over the last minute.
901 # If the load average is less than 1.0 or cannot be determined, returns 1.0.
902 sub get_load_average {
903     my ($avg) = `uptime` =~ /load average:\s*([^,]+),/;
904     return $avg >= 1.0 ? $avg : 1.0;
905 }
906
907 # Calls setitimer to set a timeout, then execs what was passed to us.
908 sub exec_setitimer {
909     if (defined $timeout) {
910         if ($\16 ge 5.8.0) {
911             eval "
912               use Time::HiRes qw(setitimer ITIMER_VIRTUAL);
913               setitimer (ITIMER_VIRTUAL, $timeout, 0);
914             ";
915         } else {
916             { exec ("setitimer-helper", $timeout, @_); };
917             exit 1 if !$!{ENOENT};
918             print STDERR "warning: setitimer-helper is not installed, so ",
919               "CPU time limit will not be enforced\n";
920         }
921     }
922     exec (@_);
923     exit (1);
924 }
925
926 sub SIGVTALRM {
927     use Config;
928     my $i = 0;
929     foreach my $name (split(' ', $Config{sig_name})) {
930         return $i if $name eq 'VTALRM';
931         $i++;
932     }
933     return 0;
934 }
935
936 # find_in_path ($program)
937 #
938 # Searches for $program in $ENV{PATH}.
939 # Returns $program if found, otherwise undef.
940 sub find_in_path {
941     my ($program) = @_;
942     -x "$_/$program" and return $program foreach split (':', $ENV{PATH});
943     return;
944 }