6 use File::Temp 'tempfile';
7 use Getopt::Long qw(:config bundling);
8 use Fcntl qw(SEEK_SET SEEK_CUR);
10 # Read Pintos.pm from the same directory as this program.
11 BEGIN { my $self = $0; $self =~ s%/+[^/]*$%%; require "$self/Pintos.pm"; }
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.
36 parse_command_line ();
37 prepare_scratch_disk ();
40 finish_scratch_disk ();
44 # Parses the command line.
45 sub parse_command_line {
46 usage (0) if @ARGV == 0 || (@ARGV == 1 && $ARGV[0] eq '--help');
49 if (grep ($_ eq '--', @kernel_args)) {
51 while ((my $arg = shift (@kernel_args)) ne '--') {
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") },
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") },
64 "m|memory=i" => \$mem,
65 "j|jitter=i" => sub { set_jitter ($_[1]) },
66 "r|realtime" => sub { set_realtime () },
68 "T|timeout=i" => \$timeout,
69 "k|kill-on-failure" => \$kill_on_failure,
71 "v|no-vga" => sub { set_vga ('none'); },
72 "s|no-serial" => sub { $serial = 0; },
73 "t|terminal" => sub { set_vga ('terminal'); },
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]); },
79 "h|help" => sub { usage (0); },
81 "kernel=s" => \&set_part,
82 "filesys=s" => \&set_part,
83 "swap=s" => \&set_part,
85 "filesys-size=s" => \&set_part,
86 "scratch-size=s" => \&set_part,
87 "swap-size=s" => \&set_part,
89 "kernel-from=s" => \&set_part,
90 "filesys-from=s" => \&set_part,
91 "swap-from=s" => \&set_part,
93 "make-disk=s" => sub { $make_disk = $_[1];
95 "disk=s" => sub { set_disk ($_[1]); },
96 "loader=s" => \$loader_fn,
98 "geometry=s" => \&set_geometry,
99 "align=s" => \&set_align)
103 $sim = "bochs" if !defined $sim;
104 $debug = "none" if !defined $debug;
105 $vga = exists ($ENV{DISPLAY}) ? "window" : "none" if !defined $vga;
107 undef $timeout, print "warning: disabling timeout with --$debug\n"
108 if defined ($timeout) && $debug ne 'none';
110 print "warning: enabling serial port for -k or --kill-on-failure\n"
111 if $kill_on_failure && !$serial;
114 print STDERR "warning: setting --align=bochs for Bochs support\n"
115 if $sim eq 'bochs' && defined ($align) && $align eq 'none';
119 # Prints a usage message and exits with $exitcode.
122 $exitcode = 1 unless defined $exitcode;
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.
129 --bochs (default) Use Bochs as simulator
130 --qemu Use QEMU as simulator
131 --player Use VMware Player as simulator
133 --no-debug (default) No debugger
134 --monitor Debug with simulator's monitor
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
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
172 -h, --help Display this help message.
177 # Sets the simulator.
180 die "--$new_sim conflicts with --$sim\n"
181 if defined ($sim) && $sim ne $new_sim;
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;
193 # Sets VGA output destination.
196 if (defined ($vga) && $vga ne $new_vga) {
197 print "warning: conflicting vga display options\n";
202 # Sets randomized timer interrupts.
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;
211 # Sets real-time timer interrupts.
213 die "--realtime conflicts with --jitter\n" if defined $jitter;
217 # add_file(\@list, $file)
219 # Adds [$file] to @list, which should be @puts or @gets.
220 # Sets $as_ref to point to the added element.
222 my ($list, $file) = @_;
224 push (@$list, $as_ref);
227 # Sets the guest/host name for the previous put/get.
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];
236 # Sets $disk as a disk to be included in the VM to run.
240 push (@disks, $disk);
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};
252 # Locates the files used to back each of the virtual disks,
253 # and creates temporary 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);
262 # Try to find file system and swap disks, if we don't already have
264 if (!exists $parts{FILESYS}) {
265 my $name = find_file ('filesys.dsk');
266 set_disk ($name) if defined $name;
268 if (!exists $parts{SWAP}) {
269 my $name = find_file ('swap.dsk');
270 set_disk ($name) if defined $name;
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";
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";
288 if (!defined $make_disk) {
289 ($handle, $make_disk) = tempfile (UNLINK => $tmp_disk,
292 die "$make_disk: already exists\n" if -e $make_disk;
293 open ($handle, '>', $make_disk) or die "$make_disk: create: $!\n";
296 # Prepare the arguments to pass to the Pintos kernel.
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;
307 for my $role (@role_order) {
308 my $p = $parts{$role};
310 next if exists $p->{DISK};
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);
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;
327 # Prepare the scratch disk for gets and puts.
328 sub prepare_scratch_disk {
329 return if !@gets && !@puts;
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)
338 write_fully ($part_handle, $part_fn, "\0" x 1024);
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);
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;
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";
361 # Set $part_fn as the source for the scratch partition.
362 do_set_part ('SCRATCH', 'file', $part_fn);
366 # Read "get" files from the scratch disk.
367 sub finish_scratch_disk {
370 # Open scratch partition.
371 my ($p) = $parts{SCRATCH};
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";
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.
385 my ($part_end) = ($p->{START} + $p->{SECTORS}) * 512;
386 foreach my $get (@gets) {
387 my ($name) = defined ($get->[1]) ? $get->[1] : $get->[0];
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";
394 print STDERR "getting $name failed ($error)\n";
398 die "$name: unlink: $!\n" if !$ok && !unlink ($name) && !$!{ENOENT};
402 # mk_ustar_field($number, $size)
404 # Returns $number in a $size-byte numeric field in the format used by
405 # the standard ustar archive header.
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;
415 # calc_ustar_chksum($s)
417 # Calculates and returns the ustar checksum of 512-byte ustar archive
419 sub calc_ustar_chksum {
421 die if length ($s) != 512;
422 substr ($s, 148, 8, ' ' x 8);
423 return unpack ("%32a*", $s);
426 # put_scratch_file($src_file_name, $dst_file_name,
427 # $disk_handle, $disk_file_name).
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) = @_;
434 print "Copying $src_file_name to scratch partition...\n";
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;
442 # Compose and write ustar header.
443 stat $src_file_name or die "$src_file_name: stat: $!\n";
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
453 . ("\0" x 100) # linkname
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);
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,
471 die "$src_file_name: changed size while being read\n"
472 if $size != -s $put_handle;
475 # Round up disk data to beginning of next sector.
476 write_fully ($disk_handle, $disk_file_name, "\0" x (512 - $size % 512))
480 # get_scratch_file($get_file_name, $disk_handle, $disk_file_name)
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) = @_;
488 print "Copying $get_file_name out of $disk_file_name...\n";
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);
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';
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;
505 my ($typeflag) = substr ($header, 156, 1);
506 return "not a regular file" if $typeflag ne '0' && $typeflag ne "\0";
509 my ($size) = oct (unpack ("Z*", substr ($header, 124, 12)));
510 return "bad size $size\n" if $size < 0;
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,
520 # Skip forward in disk up to beginning of next sector.
521 read_fully ($disk_handle, $disk_file_name, 512 - $size % 512)
527 # Running simulators.
529 # Runs the selected simulator.
531 if ($sim eq 'bochs') {
533 } elsif ($sim eq 'qemu') {
535 } elsif ($sim eq 'player') {
538 die "unknown simulator `$sim'\n";
544 # Select Bochs binary based on the chosen debugger.
545 my ($bin) = $debug eq 'monitor' ? 'bochs-dbg' : 'bochs';
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;
554 # Write bochsrc.txt configuration file.
555 open (BOCHSRC, ">", "bochsrc.txt") or die "bochsrc.txt: create: $!\n";
557 romimage: file=\$BXSHARE/BIOS-bochs-latest
558 vgaromimage: file=\$BXSHARE/VGABIOS-lgpl-latest
564 user_shortcut: keys=ctrlaltdel
566 print BOCHSRC "gdbstub: enabled=1\n" if $debug eq 'gdb';
567 print BOCHSRC "clock: sync=", $realtime ? 'realtime' : 'none',
569 print BOCHSRC "ata1: enabled=1, ioaddr1=0x170, ioaddr2=0x370, irq=15\n"
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') {
577 my $mode = defined ($squish_pty) ? "term" : "file";
578 print BOCHSRC "com1: enabled=1, mode=$mode, dev=/dev/stdout\n";
580 print BOCHSRC "display_library: nogui\n" if $vga eq 'none';
582 print BOCHSRC "display_library: term\n";
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;
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,
598 } elsif (WIFSIGNALED ($exit)) {
599 die "Bochs died with signal ", WTERMSIG ($exit), "\n";
601 die "Bochs died: code $exit\n";
605 sub print_bochs_disk_line {
606 my ($device, $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";
617 print "warning: qemu doesn't support --terminal\n"
618 if $vga eq 'terminal';
619 print "warning: qemu doesn't support jitter\n"
621 my (@cmd) = ('qemu');
622 push (@cmd, '-hda', $disks[0]) if defined $disks[0];
623 push (@cmd, '-hdb', $disks[1]) if defined $disks[1];
624 push (@cmd, '-hdc', $disks[2]) if defined $disks[2];
625 push (@cmd, '-hdd', $disks[3]) if defined $disks[3];
626 push (@cmd, '-m', $mem);
627 push (@cmd, '-net', 'none');
628 push (@cmd, '-nographic') if $vga eq 'none';
629 push (@cmd, '-serial', 'stdio') if $serial && $vga ne 'none';
630 push (@cmd, '-S') if $debug eq 'monitor';
631 push (@cmd, '-s', '-S') if $debug eq 'gdb';
632 push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none';
636 # player_unsup($flag)
638 # Prints a message that $flag is unsupported by VMware Player.
641 print "warning: no support for $flag with VMware Player\n";
644 # Runs VMware Player.
646 player_unsup ("--$debug") if $debug ne 'none';
647 player_unsup ("--no-vga") if $vga eq 'none';
648 player_unsup ("--terminal") if $vga eq 'terminal';
649 player_unsup ("--jitter") if defined $jitter;
650 player_unsup ("--timeout"), undef $timeout if defined $timeout;
651 player_unsup ("--kill-on-failure"), undef $kill_on_failure
652 if defined $kill_on_failure;
654 $mem = round_up ($mem, 4); # Memory must be multiple of 4 MB.
656 open (VMX, ">", "pintos.vmx") or die "pintos.vmx: create: $!\n";
657 chmod 0777 & ~umask, "pintos.vmx";
659 #! /usr/bin/vmware -G
663 floppy0.present = FALSE
665 sound.present = FALSE
666 gui.exitAtPowerOff = TRUE
667 gui.exitOnCLIHLT = TRUE
668 gui.powerOnAtStartUp = TRUE
671 print VMX <<EOF if $serial;
672 serial0.present = TRUE
673 serial0.fileType = "pipe"
674 serial0.fileName = "pintos.socket"
675 serial0.pipe.endPoint = "client"
676 serial0.tryNoRxLoss = "TRUE"
679 for (my ($i) = 0; $i < 4; $i++) {
680 my ($dsk) = $disks[$i];
681 last if !defined $dsk;
683 my ($device) = "ide" . int ($i / 2) . ":" . ($i % 2);
684 my ($pln) = "$device.pln";
687 $device.present = TRUE
688 $device.deviceType = "plainDisk"
689 $device.fileName = "$pln"
692 open (URANDOM, '<', '/dev/urandom') or die "/dev/urandom: open: $!\n";
694 sysread (URANDOM, $bytes, 4) == 4 or die "/dev/urandom: read: $!\n";
696 my ($cid) = unpack ("L", $bytes);
698 my (%geom) = disk_geometry ($dsk);
699 open (PLN, ">", $pln) or die "$pln: create: $!\n";
704 createType="monolithicFlat"
706 RW $geom{CAPACITY} FLAT "$dsk" 0
711 ddb.adapterType = "ide"
712 ddb.virtualHWVersion = "4"
713 ddb.toolsVersion = "2"
714 ddb.geometry.cylinders = "$geom{C}"
715 ddb.geometry.heads = "$geom{H}"
716 ddb.geometry.sectors = "$geom{S}"
724 $squish_unix = find_in_path ("squish-unix");
725 print "warning: can't find squish-unix, so terminal input ",
726 "and output will fail\n" if !defined $squish_unix;
729 my ($vmx) = getcwd () . "/pintos.vmx";
730 my (@cmd) = ("vmplayer", $vmx);
731 unshift (@cmd, $squish_unix, "pintos.socket") if $squish_unix;
732 print join (' ', @cmd), "\n";
739 my ($handle, $file_name, $size) = @_;
740 if (-s ($handle) < $size) {
741 sysseek ($handle, $size - 1, 0) == $size - 1
742 or die "$file_name: seek: $!\n";
743 syswrite ($handle, "\0") == 1
744 or die "$file_name: write: $!\n";
748 # disk_geometry($file)
750 # Examines $file and returns a valid IDE disk geometry for it, as a
754 my ($size) = -s $file;
755 die "$file: stat: $!\n" if !defined $size;
756 die "$file: size $size not a multiple of 512 bytes\n" if $size % 512;
757 my ($cyl_size) = 512 * 16 * 63;
758 my ($cylinders) = ceil ($size / $cyl_size);
760 return (CAPACITY => $size / 512,
766 # Subprocess utilities.
770 # Runs xsystem(@args).
771 # Also prints the command it's running and checks that it succeeded.
773 print join (' ', @_), "\n";
774 die "command failed\n" if xsystem (@_);
779 # Creates a subprocess via exec(@args) and waits for it to complete.
780 # Relays common signals to the subprocess.
781 # If $timeout is set then the subprocess will be killed after that long.
783 # QEMU turns off local echo and does not restore it if killed by a signal.
784 # We compensate by restoring it ourselves.
785 my $cleanup = sub {};
787 my $termios = POSIX::Termios->new;
788 $termios->getattr (0);
789 $cleanup = sub { $termios->setattr (0, &POSIX::TCSANOW); }
792 # Create pipe for filtering output.
793 pipe (my $in, my $out) or die "pipe: $!\n" if $kill_on_failure;
796 if (!defined ($pid)) {
800 # Running in child process.
801 dup2 (fileno ($out), STDOUT_FILENO) or die "dup2: $!\n"
805 # Running in parent process.
806 close $out if $kill_on_failure;
809 local $SIG{ALRM} = sub { timeout ($pid, $cause, $cleanup); };
810 local $SIG{INT} = sub { relay_signal ($pid, "INT", $cleanup); };
811 local $SIG{TERM} = sub { relay_signal ($pid, "TERM", $cleanup); };
812 alarm ($timeout * get_load_average () + 1) if defined ($timeout);
814 if ($kill_on_failure) {
820 if (waitpid ($pid, WNOHANG) != 0) {
821 # Subprocess died. Pass through any remaining data.
822 do { print $buf } while sysread ($in, $buf, 4096) > 0;
826 # Read and print out pipe data.
827 my ($len) = length ($buf);
828 waitpid ($pid, 0), last
829 if sysread ($in, $buf, 4096, $len) <= 0;
830 print substr ($buf, $len);
832 # Remove full lines from $buf and scan them for keywords.
833 while ((my $idx = index ($buf, "\n")) >= 0) {
834 local $_ = substr ($buf, 0, $idx + 1, '');
835 next if defined ($cause);
836 if (/(Kernel PANIC|User process ABORT)/ ) {
839 } elsif (/Pintos booting/ && ++$boots > 1) {
840 $cause = "triple fault";
843 $cause = "test failure";
854 if (WIFSIGNALED ($?) && WTERMSIG ($?) == SIGVTALRM ()) {
856 print "\nTIMEOUT after $timeout seconds of host CPU time\n";
864 # relay_signal($pid, $signal, &$cleanup)
866 # Relays $signal to $pid and then reinvokes it for us with the default
867 # handler. Also cleans up temporary files and invokes $cleanup.
869 my ($pid, $signal, $cleanup) = @_;
871 eval { File::Temp::cleanup() }; # Not defined in old File::Temp.
873 $SIG{$signal} = 'DEFAULT';
874 kill $signal, getpid ();
877 # timeout($pid, $cause, &$cleanup)
879 # Interrupts $pid and dies with a timeout error message,
880 # after invoking $cleanup.
882 my ($pid, $cause, $cleanup) = @_;
887 if (!defined ($cause)) {
888 my ($load_avg) = `uptime` =~ /(load average:.*)$/i;
889 print "\nTIMEOUT after ", time () - $start_time,
890 " seconds of wall-clock time";
891 print " - $load_avg" if defined $load_avg;
894 print "Simulation terminated due to $cause.\n";
899 # Returns the system load average over the last minute.
900 # If the load average is less than 1.0 or cannot be determined, returns 1.0.
901 sub get_load_average {
902 my ($avg) = `uptime` =~ /load average:\s*([^,]+),/;
903 return $avg >= 1.0 ? $avg : 1.0;
906 # Calls setitimer to set a timeout, then execs what was passed to us.
908 if (defined $timeout) {
911 use Time::HiRes qw(setitimer ITIMER_VIRTUAL);
912 setitimer (ITIMER_VIRTUAL, $timeout, 0);
915 { exec ("setitimer-helper", $timeout, @_); };
916 exit 1 if !$!{ENOENT};
917 print STDERR "warning: setitimer-helper is not installed, so ",
918 "CPU time limit will not be enforced\n";
928 foreach my $name (split(' ', $Config{sig_name})) {
929 return $i if $name eq 'VTALRM';
935 # find_in_path ($program)
937 # Searches for $program in $ENV{PATH}.
938 # Returns $program if found, otherwise undef.
941 -x "$_/$program" and return $program foreach split (':', $ENV{PATH});