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.
35 our ($gdb_port) = $ENV{"GDB_PORT"} || "1234"; # Port to listen on for GDB
37 parse_command_line ();
38 prepare_scratch_disk ();
41 finish_scratch_disk ();
45 # Parses the command line.
46 sub parse_command_line {
47 usage (0) if @ARGV == 0 || (@ARGV == 1 && $ARGV[0] eq '--help');
50 if (grep ($_ eq '--', @kernel_args)) {
52 while ((my $arg = shift (@kernel_args)) ne '--') {
55 GetOptions ("sim=s" => sub { set_sim ($_[1]) },
56 "bochs" => sub { set_sim ("bochs") },
57 "qemu" => sub { set_sim ("qemu") },
58 "player" => sub { set_sim ("player") },
60 "debug=s" => sub { set_debug ($_[1]) },
61 "no-debug" => sub { set_debug ("none") },
62 "monitor" => sub { set_debug ("monitor") },
63 "gdb" => sub { set_debug ("gdb") },
65 "m|memory=i" => \$mem,
66 "j|jitter=i" => sub { set_jitter ($_[1]) },
67 "r|realtime" => sub { set_realtime () },
69 "T|timeout=i" => \$timeout,
70 "k|kill-on-failure" => \$kill_on_failure,
72 "v|no-vga" => sub { set_vga ('none'); },
73 "s|no-serial" => sub { $serial = 0; },
74 "t|terminal" => sub { set_vga ('terminal'); },
76 "p|put-file=s" => sub { add_file (\@puts, $_[1]); },
77 "g|get-file=s" => sub { add_file (\@gets, $_[1]); },
78 "a|as=s" => sub { set_as ($_[1]); },
80 "h|help" => sub { usage (0); },
82 "kernel=s" => \&set_part,
83 "filesys=s" => \&set_part,
84 "swap=s" => \&set_part,
86 "filesys-size=s" => \&set_part,
87 "scratch-size=s" => \&set_part,
88 "swap-size=s" => \&set_part,
90 "kernel-from=s" => \&set_part,
91 "filesys-from=s" => \&set_part,
92 "swap-from=s" => \&set_part,
94 "make-disk=s" => sub { $make_disk = $_[1];
96 "disk=s" => sub { set_disk ($_[1]); },
97 "loader=s" => \$loader_fn,
99 "geometry=s" => \&set_geometry,
100 "align=s" => \&set_align)
104 $sim = "bochs" if !defined $sim;
105 $debug = "none" if !defined $debug;
106 $vga = exists ($ENV{DISPLAY}) ? "window" : "none" if !defined $vga;
108 undef $timeout, print "warning: disabling timeout with --$debug\n"
109 if defined ($timeout) && $debug ne 'none';
111 print "warning: enabling serial port for -k or --kill-on-failure\n"
112 if $kill_on_failure && !$serial;
115 print STDERR "warning: setting --align=bochs for Bochs support\n"
116 if $sim eq 'bochs' && defined ($align) && $align eq 'none';
118 $kill_on_failure = 0;
122 # Prints a usage message and exits with $exitcode.
125 $exitcode = 1 unless defined $exitcode;
127 pintos, a utility for running Pintos in a simulator
128 Usage: pintos [OPTION...] -- [ARGUMENT...]
129 where each OPTION is one of the following options
130 and each ARGUMENT is passed to Pintos kernel verbatim.
132 --bochs (default) Use Bochs as simulator
133 --qemu Use QEMU as simulator
134 --player Use VMware Player as simulator
136 --no-debug (default) No debugger
137 --monitor Debug with simulator's monitor
139 Display options: (default is both VGA and serial)
140 -v, --no-vga No VGA display or keyboard
141 -s, --no-serial No serial input or output
142 -t, --terminal Display VGA in terminal (Bochs only)
143 Timing options: (Bochs only)
144 -j SEED Randomize timer interrupts
145 -r, --realtime Use realistic, not reproducible, timings
147 -T, --timeout=N Kill Pintos after N seconds CPU time or N*load_avg
148 seconds wall-clock time (whichever comes first)
149 -k, --kill-on-failure Kill Pintos a few seconds after a kernel or user
150 panic, test failure, or triple fault
151 Configuration options:
152 -m, --mem=N Give Pintos N MB physical RAM (default: 4)
153 File system commands:
154 -p, --put-file=HOSTFN Copy HOSTFN into VM, by default under same name
155 -g, --get-file=GUESTFN Copy GUESTFN out of VM, by default under same name
156 -a, --as=FILENAME Specifies guest (for -p) or host (for -g) file name
157 Partition options: (where PARTITION is one of: kernel filesys scratch swap)
158 --PARTITION=FILE Use a copy of FILE for the given PARTITION
159 --PARTITION-size=SIZE Create an empty PARTITION of the given SIZE in MB
160 --PARTITION-from=DISK Use of a copy of the given PARTITION in DISK
161 (There is no --kernel-size, --scratch, or --scratch-from option.)
162 Disk configuration options:
163 --make-disk=DISK Name the new DISK and don't delete it after the run
164 --disk=DISK Also use existing DISK (may be used multiple times)
165 Advanced disk configuration options:
166 --loader=FILE Use FILE as bootstrap loader (default: loader.bin)
167 --geometry=H,S Use H head, S sector geometry (default: 16,63)
168 --geometry=zip Use 64 head, 32 sector geometry for USB-ZIP boot
169 (see http://syslinux.zytor.com/usbkey.php)
170 --align=bochs Pad out disk to cylinder to support Bochs (default)
171 --align=full Align partition boundaries to cylinder boundary to
172 let fdisk guess correct geometry and quiet warnings
173 --align=none Don't align partitions at all, to save space
175 -h, --help Display this help message.
180 # Sets the simulator.
183 die "--$new_sim conflicts with --$sim\n"
184 if defined ($sim) && $sim ne $new_sim;
190 my ($new_debug) = @_;
191 die "--$new_debug conflicts with --$debug\n"
192 if $debug ne 'none' && $new_debug ne 'none' && $debug ne $new_debug;
196 # Sets VGA output destination.
199 if (defined ($vga) && $vga ne $new_vga) {
200 print "warning: conflicting vga display options\n";
205 # Sets randomized timer interrupts.
207 my ($new_jitter) = @_;
208 die "--realtime conflicts with --jitter\n" if defined $realtime;
209 die "different --jitter already defined\n"
210 if defined $jitter && $jitter != $new_jitter;
211 $jitter = $new_jitter;
214 # Sets real-time timer interrupts.
216 die "--realtime conflicts with --jitter\n" if defined $jitter;
220 # add_file(\@list, $file)
222 # Adds [$file] to @list, which should be @puts or @gets.
223 # Sets $as_ref to point to the added element.
225 my ($list, $file) = @_;
227 push (@$list, $as_ref);
230 # Sets the guest/host name for the previous put/get.
233 die "-a (or --as) is only allowed after -p or -g\n" if !defined $as_ref;
234 die "Only one -a (or --as) is allowed after -p or -g\n"
235 if defined $as_ref->[1];
239 # Sets $disk as a disk to be included in the VM to run.
243 push (@disks, $disk);
245 my (%pt) = read_partition_table ($disk);
246 for my $role (keys %pt) {
247 die "can't have two sources for \L$role\E partition"
248 if exists $parts{$role};
249 $parts{$role}{DISK} = $disk;
250 $parts{$role}{START} = $pt{$role}{START};
251 $parts{$role}{SECTORS} = $pt{$role}{SECTORS};
255 # Locates the files used to back each of the virtual disks,
256 # and creates temporary disks.
258 # Find kernel, if we don't already have one.
259 if (!exists $parts{KERNEL}) {
260 my $name = find_file ('kernel.bin');
261 die "Cannot find kernel\n" if !defined $name;
262 do_set_part ('KERNEL', 'file', $name);
265 # Try to find file system and swap disks, if we don't already have
267 if (!exists $parts{FILESYS}) {
268 my $name = find_file ('filesys.dsk');
269 set_disk ($name) if defined $name;
271 if (!exists $parts{SWAP}) {
272 my $name = find_file ('swap.dsk');
273 set_disk ($name) if defined $name;
276 # Warn about (potentially) missing partitions.
277 if (my ($project) = `pwd` =~ /\b(threads|userprog|vm|filesys)\b/) {
278 if ((grep ($project eq $_, qw (userprog vm filesys)))
279 && !defined $parts{FILESYS}) {
280 print STDERR "warning: it looks like you're running the $project ";
281 print STDERR "project, but no file system partition is present\n";
283 if ($project eq 'vm' && !defined $parts{SWAP}) {
284 print STDERR "warning: it looks like you're running the $project ";
285 print STDERR "project, but no swap partition is present\n";
291 if (!defined $make_disk) {
292 ($handle, $make_disk) = tempfile (UNLINK => $tmp_disk,
295 die "$make_disk: already exists\n" if -e $make_disk;
296 open ($handle, '>', $make_disk) or die "$make_disk: create: $!\n";
299 # Prepare the arguments to pass to the Pintos kernel.
301 push (@args, shift (@kernel_args))
302 while @kernel_args && $kernel_args[0] =~ /^-/;
303 push (@args, 'extract') if @puts;
304 push (@args, @kernel_args);
305 push (@args, 'append', $_->[0]) foreach @gets;
310 for my $role (@role_order) {
311 my $p = $parts{$role};
313 next if exists $p->{DISK};
316 $disk{DISK} = $make_disk;
317 $disk{HANDLE} = $handle;
318 $disk{ALIGN} = $align;
319 $disk{GEOMETRY} = %geometry;
320 $disk{FORMAT} = 'partitioned';
321 $disk{LOADER} = read_loader ($loader_fn);
322 $disk{ARGS} = \@args;
323 assemble_disk (%disk);
325 # Put the disk at the front of the list of disks.
326 unshift (@disks, $make_disk);
327 die "can't use more than " . scalar (@disks) . "disks\n" if @disks > 4;
330 # Prepare the scratch disk for gets and puts.
331 sub prepare_scratch_disk {
332 return if !@gets && !@puts;
334 my ($p) = $parts{SCRATCH};
335 # Create temporary partition and write the files to put to it,
336 # then write an end-of-archive marker.
337 my ($part_handle, $part_fn) = tempfile (UNLINK => 1, SUFFIX => '.part');
338 put_scratch_file ($_->[0], defined $_->[1] ? $_->[1] : $_->[0],
339 $part_handle, $part_fn)
341 write_fully ($part_handle, $part_fn, "\0" x 1024);
343 # Make sure the scratch disk is big enough to get big files
344 # and at least as big as any requested size.
345 my ($size) = round_up (max (@gets * 1024 * 1024, $p->{BYTES} || 0), 512);
346 extend_file ($part_handle, $part_fn, $size);
347 close ($part_handle);
349 if (exists $p->{DISK}) {
350 # Copy the scratch partition to the disk.
351 die "$p->{DISK}: scratch partition too small\n"
352 if $p->{SECTORS} * 512 < $size;
355 open ($part_handle, '<', $part_fn) or die "$part_fn: open: $!\n";
356 open ($disk_handle, '+<', $p->{DISK}) or die "$p->{DISK}: open: $!\n";
357 my ($start) = $p->{START} * 512;
358 sysseek ($disk_handle, $start, SEEK_SET) == $start
359 or die "$p->{DISK}: seek: $!\n";
360 copy_file ($part_handle, $part_fn, $disk_handle, $p->{DISK}, $size);
361 close ($disk_handle) or die "$p->{DISK}: close: $!\n";
362 close ($part_handle) or die "$part_fn: close: $!\n";
364 # Set $part_fn as the source for the scratch partition.
365 do_set_part ('SCRATCH', 'file', $part_fn);
369 # Read "get" files from the scratch disk.
370 sub finish_scratch_disk {
373 # Open scratch partition.
374 my ($p) = $parts{SCRATCH};
376 my ($part_fn) = $p->{DISK};
377 open ($part_handle, '<', $part_fn) or die "$part_fn: open: $!\n";
378 sysseek ($part_handle, $p->{START} * 512, SEEK_SET) == $p->{START} * 512
379 or die "$part_fn: seek: $!\n";
382 # If reading fails, delete that file and all subsequent files, but
383 # don't die with an error, because that's a guest error not a host
384 # error. (If we do exit with an error code, it fouls up the
385 # grading process.) Instead, just make sure that the host file(s)
386 # we were supposed to retrieve is unlinked.
388 my ($part_end) = ($p->{START} + $p->{SECTORS}) * 512;
389 foreach my $get (@gets) {
390 my ($name) = defined ($get->[1]) ? $get->[1] : $get->[0];
392 my ($error) = get_scratch_file ($name, $part_handle, $part_fn);
393 if (!$error && sysseek ($part_handle, 0, SEEK_CUR) > $part_end) {
394 $error = "$part_fn: scratch data overflows partition";
397 print STDERR "getting $name failed ($error)\n";
401 die "$name: unlink: $!\n" if !$ok && !unlink ($name) && !$!{ENOENT};
405 # mk_ustar_field($number, $size)
407 # Returns $number in a $size-byte numeric field in the format used by
408 # the standard ustar archive header.
410 my ($number, $size) = @_;
411 my ($len) = $size - 1;
412 my ($out) = sprintf ("%0${len}o", $number) . "\0";
413 die "$number: too large for $size-byte octal ustar field\n"
414 if length ($out) != $size;
418 # calc_ustar_chksum($s)
420 # Calculates and returns the ustar checksum of 512-byte ustar archive
422 sub calc_ustar_chksum {
424 die if length ($s) != 512;
425 substr ($s, 148, 8, ' ' x 8);
426 return unpack ("%32a*", $s);
429 # put_scratch_file($src_file_name, $dst_file_name,
430 # $disk_handle, $disk_file_name).
432 # Copies $src_file_name into $disk_handle for extraction as
433 # $dst_file_name. $disk_file_name is used for error messages.
434 sub put_scratch_file {
435 my ($src_file_name, $dst_file_name, $disk_handle, $disk_file_name) = @_;
437 print "Copying $src_file_name to scratch partition...\n";
439 # ustar format supports up to 100 characters for a file name, and
440 # even longer names given some common properties, but our code in
441 # the Pintos kernel only supports at most 99 characters.
442 die "$dst_file_name: name too long (max 99 characters)\n"
443 if length ($dst_file_name) > 99;
445 # Compose and write ustar header.
446 stat $src_file_name or die "$src_file_name: stat: $!\n";
448 my ($header) = (pack ("a100", $dst_file_name) # name
449 . mk_ustar_field (0644, 8) # mode
450 . mk_ustar_field (0, 8) # uid
451 . mk_ustar_field (0, 8) # gid
452 . mk_ustar_field ($size, 12) # size
453 . mk_ustar_field (1136102400, 12) # mtime
456 . ("\0" x 100) # linkname
459 . "root" . ("\0" x 28) # uname
460 . "root" . ("\0" x 28) # gname
461 . "\0" x 8 # devmajor
462 . "\0" x 8 # devminor
463 . ("\0" x 155)) # prefix
464 . "\0" x 12; # pad to 512 bytes
465 substr ($header, 148, 8) = mk_ustar_field (calc_ustar_chksum ($header), 8);
466 write_fully ($disk_handle, $disk_file_name, $header);
470 sysopen ($put_handle, $src_file_name, O_RDONLY)
471 or die "$src_file_name: open: $!\n";
472 copy_file ($put_handle, $src_file_name, $disk_handle, $disk_file_name,
474 die "$src_file_name: changed size while being read\n"
475 if $size != -s $put_handle;
478 # Round up disk data to beginning of next sector.
479 write_fully ($disk_handle, $disk_file_name, "\0" x (512 - $size % 512))
483 # get_scratch_file($get_file_name, $disk_handle, $disk_file_name)
485 # Copies from $disk_handle to $get_file_name (which is created).
486 # $disk_file_name is used for error messages.
487 # Returns 1 if successful, 0 on failure.
488 sub get_scratch_file {
489 my ($get_file_name, $disk_handle, $disk_file_name) = @_;
491 print "Copying $get_file_name out of $disk_file_name...\n";
493 # Read ustar header sector.
494 my ($header) = read_fully ($disk_handle, $disk_file_name, 512);
495 return "scratch disk tar archive ends unexpectedly"
496 if $header eq ("\0" x 512);
498 # Verify magic numbers.
499 return "corrupt ustar signature" if substr ($header, 257, 6) ne "ustar\0";
500 return "invalid ustar version" if substr ($header, 263, 2) ne '00';
503 my ($chksum) = oct (unpack ("Z*", substr ($header, 148, 8)));
504 my ($correct_chksum) = calc_ustar_chksum ($header);
505 return "checksum mismatch" if $chksum != $correct_chksum;
508 my ($typeflag) = substr ($header, 156, 1);
509 return "not a regular file" if $typeflag ne '0' && $typeflag ne "\0";
512 my ($size) = oct (unpack ("Z*", substr ($header, 124, 12)));
513 return "bad size $size\n" if $size < 0;
517 sysopen ($get_handle, $get_file_name, O_WRONLY | O_CREAT, 0666)
518 or die "$get_file_name: create: $!\n";
519 copy_file ($disk_handle, $disk_file_name, $get_handle, $get_file_name,
523 # Skip forward in disk up to beginning of next sector.
524 read_fully ($disk_handle, $disk_file_name, 512 - $size % 512)
530 # Running simulators.
532 # Runs the selected simulator.
534 if ($sim eq 'bochs') {
536 } elsif ($sim eq 'qemu') {
538 } elsif ($sim eq 'player') {
541 die "unknown simulator `$sim'\n";
547 # Select Bochs binary based on the chosen debugger.
548 my ($bin) = $debug eq 'monitor' ? 'bochs-dbg' : 'bochs';
552 $squish_pty = find_in_path ("squish-pty");
553 print "warning: can't find squish-pty, so terminal input will fail\n"
554 if !defined $squish_pty;
557 # Write bochsrc.txt configuration file.
558 open (BOCHSRC, ">", "bochsrc.txt") or die "bochsrc.txt: create: $!\n";
560 romimage: file=\$BXSHARE/BIOS-bochs-latest
561 vgaromimage: file=\$BXSHARE/VGABIOS-lgpl-latest
568 #user_shortcut: keys=ctrlaltdel
569 # For more recent bochs:
570 keyboard: user_shortcut=ctrl-alt-del
572 print BOCHSRC "gdbstub: enabled=1, port=$gdb_port\n" if $debug eq 'gdb';
573 print BOCHSRC "clock: sync=", $realtime ? 'realtime' : 'none',
575 print BOCHSRC "ata1: enabled=1, ioaddr1=0x170, ioaddr2=0x370, irq=15\n"
577 print_bochs_disk_line ("ata0-master", $disks[0]);
578 print_bochs_disk_line ("ata0-slave", $disks[1]);
579 print_bochs_disk_line ("ata1-master", $disks[2]);
580 print_bochs_disk_line ("ata1-slave", $disks[3]);
581 if ($vga ne 'terminal') {
583 my $mode = defined ($squish_pty) ? "term" : "file";
584 print BOCHSRC "com1: enabled=1, mode=$mode, dev=/dev/stdout\n";
586 print BOCHSRC "display_library: nogui\n" if $vga eq 'none';
588 print BOCHSRC "display_library: term\n";
592 # Compose Bochs command line.
593 my (@cmd) = ($bin, '-q');
594 unshift (@cmd, $squish_pty) if defined $squish_pty;
595 push (@cmd, '-j', $jitter) if defined $jitter;
598 print join (' ', @cmd), "\n";
599 my ($exit) = xsystem (@cmd);
600 if (WIFEXITED ($exit)) {
601 # Bochs exited normally.
602 # Ignore the exit code; Bochs normally exits with status 1,
604 } elsif (WIFSIGNALED ($exit)) {
605 die "Bochs died with signal ", WTERMSIG ($exit), "\n";
607 die "Bochs died: code $exit\n";
611 sub print_bochs_disk_line {
612 my ($device, $disk) = @_;
614 my (%geom) = disk_geometry ($disk);
615 print BOCHSRC "$device: type=disk, path=$disk, mode=flat, ";
616 print BOCHSRC "cylinders=$geom{C}, heads=$geom{H}, spt=$geom{S}, ";
617 print BOCHSRC "translation=none\n";
623 print "warning: qemu doesn't support --terminal\n"
624 if $vga eq 'terminal';
625 print "warning: qemu doesn't support jitter\n"
627 my (@cmd) = ('qemu-system-i386');
628 push (@cmd, '-device', 'isa-debug-exit');
631 for ($i = 0; $i < 4; $i++) {
632 if (defined $disks[$i]) {
633 push (@cmd, '-drive');
634 push (@cmd, "file=$disks[$i],format=raw,index=$i,media=disk");
637 # push (@cmd, '-hda', $disks[0]) if defined $disks[0];
638 # push (@cmd, '-hdb', $disks[1]) if defined $disks[1];
639 # push (@cmd, '-hdc', $disks[2]) if defined $disks[2];
640 # push (@cmd, '-hdd', $disks[3]) if defined $disks[3];
641 push (@cmd, '-m', $mem);
642 push (@cmd, '-net', 'none');
643 push (@cmd, '-nographic') if $vga eq 'none';
644 push (@cmd, '-serial', 'stdio') if $serial && $vga ne 'none';
645 push (@cmd, '-S') if $debug eq 'monitor';
646 push (@cmd, '-gdb', "tcp::$gdb_port", '-S') if $debug eq 'gdb';
647 push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none';
651 # player_unsup($flag)
653 # Prints a message that $flag is unsupported by VMware Player.
656 print "warning: no support for $flag with VMware Player\n";
659 # Runs VMware Player.
661 player_unsup ("--$debug") if $debug ne 'none';
662 player_unsup ("--no-vga") if $vga eq 'none';
663 player_unsup ("--terminal") if $vga eq 'terminal';
664 player_unsup ("--jitter") if defined $jitter;
665 player_unsup ("--timeout"), undef $timeout if defined $timeout;
666 player_unsup ("--kill-on-failure"), undef $kill_on_failure
667 if defined $kill_on_failure;
669 $mem = round_up ($mem, 4); # Memory must be multiple of 4 MB.
671 open (VMX, ">", "pintos.vmx") or die "pintos.vmx: create: $!\n";
672 chmod 0777 & ~umask, "pintos.vmx";
674 #! /usr/bin/vmware -G
678 floppy0.present = FALSE
680 sound.present = FALSE
681 gui.exitAtPowerOff = TRUE
682 gui.exitOnCLIHLT = TRUE
683 gui.powerOnAtStartUp = TRUE
686 print VMX <<EOF if $serial;
687 serial0.present = TRUE
688 serial0.fileType = "pipe"
689 serial0.fileName = "pintos.socket"
690 serial0.pipe.endPoint = "client"
691 serial0.tryNoRxLoss = "TRUE"
694 for (my ($i) = 0; $i < 4; $i++) {
695 my ($dsk) = $disks[$i];
696 last if !defined $dsk;
698 my ($device) = "ide" . int ($i / 2) . ":" . ($i % 2);
699 my ($pln) = "$device.pln";
702 $device.present = TRUE
703 $device.deviceType = "plainDisk"
704 $device.fileName = "$pln"
707 open (URANDOM, '<', '/dev/urandom') or die "/dev/urandom: open: $!\n";
709 sysread (URANDOM, $bytes, 4) == 4 or die "/dev/urandom: read: $!\n";
711 my ($cid) = unpack ("L", $bytes);
713 my (%geom) = disk_geometry ($dsk);
714 open (PLN, ">", $pln) or die "$pln: create: $!\n";
719 createType="monolithicFlat"
721 RW $geom{CAPACITY} FLAT "$dsk" 0
726 ddb.adapterType = "ide"
727 ddb.virtualHWVersion = "4"
728 ddb.toolsVersion = "2"
729 ddb.geometry.cylinders = "$geom{C}"
730 ddb.geometry.heads = "$geom{H}"
731 ddb.geometry.sectors = "$geom{S}"
739 $squish_unix = find_in_path ("squish-unix");
740 print "warning: can't find squish-unix, so terminal input ",
741 "and output will fail\n" if !defined $squish_unix;
744 my ($vmx) = getcwd () . "/pintos.vmx";
745 my (@cmd) = ("vmplayer", $vmx);
746 unshift (@cmd, $squish_unix, "pintos.socket") if $squish_unix;
747 print join (' ', @cmd), "\n";
754 my ($handle, $file_name, $size) = @_;
755 if (-s ($handle) < $size) {
756 sysseek ($handle, $size - 1, 0) == $size - 1
757 or die "$file_name: seek: $!\n";
758 syswrite ($handle, "\0") == 1
759 or die "$file_name: write: $!\n";
763 # disk_geometry($file)
765 # Examines $file and returns a valid IDE disk geometry for it, as a
769 my ($size) = -s $file;
770 die "$file: stat: $!\n" if !defined $size;
771 die "$file: size $size not a multiple of 512 bytes\n" if $size % 512;
772 my ($cyl_size) = 512 * 16 * 63;
773 my ($cylinders) = ceil ($size / $cyl_size);
775 return (CAPACITY => $size / 512,
781 # Subprocess utilities.
785 # Runs xsystem(@args).
786 # Also prints the command it's running and checks that it succeeded.
788 print join (' ', @_), "\n";
789 die "command failed\n" if xsystem (@_);
794 # Creates a subprocess via exec(@args) and waits for it to complete.
795 # Relays common signals to the subprocess.
796 # If $timeout is set then the subprocess will be killed after that long.
798 # QEMU turns off local echo and does not restore it if killed by a signal.
799 # We compensate by restoring it ourselves.
800 my $cleanup = sub {};
802 my $termios = POSIX::Termios->new;
803 $termios->getattr (0);
804 $cleanup = sub { $termios->setattr (0, &POSIX::TCSANOW); }
807 # Create pipe for filtering output.
808 pipe (my $in, my $out) or die "pipe: $!\n" if $kill_on_failure;
811 if (!defined ($pid)) {
815 # Running in child process.
816 dup2 (fileno ($out), STDOUT_FILENO) or die "dup2: $!\n"
820 # Running in parent process.
821 close $out if $kill_on_failure;
824 local $SIG{ALRM} = sub { timeout ($pid, $cause, $cleanup); };
825 local $SIG{INT} = sub { relay_signal ($pid, "INT", $cleanup); };
826 local $SIG{TERM} = sub { relay_signal ($pid, "TERM", $cleanup); };
827 alarm ($timeout * get_load_average () + 1) if defined ($timeout);
829 if ($kill_on_failure) {
835 if (waitpid ($pid, WNOHANG) != 0) {
836 # Subprocess died. Pass through any remaining data.
837 do { print $buf } while sysread ($in, $buf, 4096) > 0;
841 # Read and print out pipe data.
842 my ($len) = length ($buf);
843 my ($n_read) = sysread ($in, $buf, 4096, $len);
844 waitpid ($pid, 0), last if !defined ($n_read) || $n_read <= 0;
845 print substr ($buf, $len);
847 # Remove full lines from $buf and scan them for keywords.
848 while ((my $idx = index ($buf, "\n")) >= 0) {
849 local $_ = substr ($buf, 0, $idx + 1, '');
850 next if defined ($cause);
851 if (/(Kernel PANIC|User process ABORT)/ ) {
854 } elsif (/Pintos booting/ && ++$boots > 1) {
855 $cause = "triple fault";
858 $cause = "test failure";
869 if (WIFSIGNALED ($?) && WTERMSIG ($?) == SIGVTALRM_number ()) {
871 print "\nTIMEOUT after $timeout seconds of host CPU time\n";
875 # Kind of a gross hack, because qemu's isa-debug-exit device
876 # only allows odd-numbered exit values, so we can't exit
877 # cleanly with 0. We use exit status 0x63 as an alternate
878 # "clean" exit status.
879 return ($? != 0x6300) && $?;
883 # relay_signal($pid, $signal, &$cleanup)
885 # Relays $signal to $pid and then reinvokes it for us with the default
886 # handler. Also cleans up temporary files and invokes $cleanup.
888 my ($pid, $signal, $cleanup) = @_;
890 eval { File::Temp::cleanup() }; # Not defined in old File::Temp.
892 $SIG{$signal} = 'DEFAULT';
893 kill $signal, getpid ();
896 # timeout($pid, $cause, &$cleanup)
898 # Interrupts $pid and dies with a timeout error message,
899 # after invoking $cleanup.
901 my ($pid, $cause, $cleanup) = @_;
906 if (!defined ($cause)) {
907 my ($load_avg) = `uptime` =~ /(load average:.*)$/i;
908 print "\nTIMEOUT after ", time () - $start_time,
909 " seconds of wall-clock time";
910 print " - $load_avg" if defined $load_avg;
913 print "Simulation terminated due to $cause.\n";
918 # Returns the system load average over the last minute.
919 # If the load average is less than 1.0 or cannot be determined, returns 1.0.
920 sub get_load_average {
921 my ($avg) = `uptime` =~ /load average:\s*([^,]+),/;
922 return $avg >= 1.0 ? $avg : 1.0;
925 # Calls setitimer to set a timeout, then execs what was passed to us.
927 if (defined $timeout) {
930 use Time::HiRes qw(setitimer ITIMER_VIRTUAL);
931 setitimer (ITIMER_VIRTUAL, $timeout, 0);
934 { exec ("setitimer-helper", $timeout, @_); };
935 exit 1 if !$!{ENOENT};
936 print STDERR "warning: setitimer-helper is not installed, so ",
937 "CPU time limit will not be enforced\n";
944 sub SIGVTALRM_number {
947 foreach my $name (split(' ', $Config{sig_name})) {
948 return $i if $name eq 'VTALRM';
954 # find_in_path ($program)
956 # Searches for $program in $ENV{PATH}.
957 # Returns $program if found, otherwise undef.
960 -x "$_/$program" and return $program foreach split (':', $ENV{PATH});