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 ($fake_usb) = 0; # Use fake USB disks instead of IDE?
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") },
59 "hardware" => sub { set_sim ("hardware") },
61 "debug=s" => sub { set_debug ($_[1]) },
62 "no-debug" => sub { set_debug ("none") },
63 "monitor" => sub { set_debug ("monitor") },
64 "gdb" => sub { set_debug ("gdb") },
66 "m|memory=i" => \$mem,
67 "j|jitter=i" => sub { set_jitter ($_[1]) },
68 "r|realtime" => sub { set_realtime () },
70 "T|timeout=i" => \$timeout,
71 "k|kill-on-failure" => \$kill_on_failure,
73 "v|no-vga" => sub { set_vga ('none'); },
74 "s|no-serial" => sub { $serial = 0; },
75 "t|terminal" => sub { set_vga ('terminal'); },
77 "p|put-file=s" => sub { add_file (\@puts, $_[1]); },
78 "g|get-file=s" => sub { add_file (\@gets, $_[1]); },
79 "a|as=s" => sub { set_as ($_[1]); },
81 "h|help" => sub { usage (0); },
83 "kernel=s" => \&set_part,
84 "filesys=s" => \&set_part,
85 "swap=s" => \&set_part,
87 "filesys-size=s" => \&set_part,
88 "scratch-size=s" => \&set_part,
89 "swap-size=s" => \&set_part,
91 "kernel-from=s" => \&set_part,
92 "filesys-from=s" => \&set_part,
93 "swap-from=s" => \&set_part,
95 "make-disk=s" => sub { $make_disk = $_[1];
97 "disk=s" => sub { set_disk ($_[1]); },
98 "loader=s" => \$loader_fn,
99 "fake-usb" => \$fake_usb,
101 "geometry=s" => \&set_geometry,
102 "align=s" => \&set_align)
106 $sim = "bochs" if !defined $sim;
107 $debug = "none" if !defined $debug;
108 $vga = exists ($ENV{DISPLAY}) ? "window" : "none" if !defined $vga;
110 if ($sim eq 'hardware') {
111 $make_disk = "pintos.dsk" if !defined $make_disk;
113 $align = 'full' if !defined $align;
116 $fake_usb = 0, print "warning: ignoring --fake-usb with $sim simulator\n"
117 if $fake_usb && $sim ne 'qemu';
119 undef $timeout, print "warning: disabling timeout with --$debug\n"
120 if defined ($timeout) && $debug ne 'none';
122 print "warning: enabling serial port for -k or --kill-on-failure\n"
123 if $kill_on_failure && !$serial;
126 print STDERR "warning: setting --align=bochs for Bochs support\n"
127 if $sim eq 'bochs' && defined ($align) && $align eq 'none';
131 # Prints a usage message and exits with $exitcode.
134 $exitcode = 1 unless defined $exitcode;
136 pintos, a utility for running Pintos in a simulator
137 Usage: pintos [OPTION...] -- [ARGUMENT...]
138 where each OPTION is one of the following options
139 and each ARGUMENT is passed to Pintos kernel verbatim.
141 --bochs (default) Use Bochs as simulator
142 --qemu Use QEMU as simulator
143 --player Use VMware Player as simulator
144 --hardware Don't run simulator; create images for real hardware
146 --no-debug (default) No debugger
147 --monitor Debug with simulator's monitor
149 Display options: (default is both VGA and serial)
150 -v, --no-vga No VGA display or keyboard
151 -s, --no-serial No serial input or output
152 -t, --terminal Display VGA in terminal (Bochs only)
153 Timing options: (Bochs only)
154 -j SEED Randomize timer interrupts
155 -r, --realtime Use realistic, not reproducible, timings
157 -T, --timeout=N Kill Pintos after N seconds CPU time or N*load_avg
158 seconds wall-clock time (whichever comes first)
159 -k, --kill-on-failure Kill Pintos a few seconds after a kernel or user
160 panic, test failure, or triple fault
161 Configuration options:
162 -m, --mem=N Give Pintos N MB physical RAM (default: 4)
163 File system commands:
164 -p, --put-file=HOSTFN Copy HOSTFN into VM, by default under same name
165 -g, --get-file=GUESTFN Copy GUESTFN out of VM, by default under same name
166 -a, --as=FILENAME Specifies guest (for -p) or host (for -g) file name
167 Partition options: (where PARTITION is one of: kernel filesys scratch swap)
168 --PARTITION=FILE Use a copy of FILE for the given PARTITION
169 --PARTITION-size=SIZE Create an empty PARTITION of the given SIZE in MB
170 --PARTITION-from=DISK Use of a copy of the given PARTITION in DISK
171 (There is no --kernel-size, --scratch, or --scratch-from option.)
172 Disk configuration options:
173 --make-disk=DISK Name the new DISK and don't delete it after the run
174 --disk=DISK Also use existing DISK (may be used multiple times)
175 Advanced disk configuration options:
176 --loader=FILE Use FILE as bootstrap loader (default: loader.bin)
177 --geometry=H,S Use H head, S sector geometry (default: 16,63)
178 --geometry=zip Use 64 head, 32 sector geometry for USB-ZIP boot
179 (see http://syslinux.zytor.com/usbkey.php)
180 --align=bochs Pad out disk to cylinder to support Bochs (default)
181 --align=full Align partition boundaries to cylinder boundary to
182 let fdisk guess correct geometry and quiet warnings
183 --align=none Don't align partitions at all, to save space
184 --fake-usb Use USB disks, not IDE, except for boot (qemu only)
186 -h, --help Display this help message.
191 # Sets the simulator.
194 die "--$new_sim conflicts with --$sim\n"
195 if defined ($sim) && $sim ne $new_sim;
201 my ($new_debug) = @_;
202 die "--$new_debug conflicts with --$debug\n"
203 if $debug ne 'none' && $new_debug ne 'none' && $debug ne $new_debug;
207 # Sets VGA output destination.
210 if (defined ($vga) && $vga ne $new_vga) {
211 print "warning: conflicting vga display options\n";
216 # Sets randomized timer interrupts.
218 my ($new_jitter) = @_;
219 die "--realtime conflicts with --jitter\n" if defined $realtime;
220 die "different --jitter already defined\n"
221 if defined $jitter && $jitter != $new_jitter;
222 $jitter = $new_jitter;
225 # Sets real-time timer interrupts.
227 die "--realtime conflicts with --jitter\n" if defined $jitter;
231 # add_file(\@list, $file)
233 # Adds [$file] to @list, which should be @puts or @gets.
234 # Sets $as_ref to point to the added element.
236 my ($list, $file) = @_;
238 push (@$list, $as_ref);
241 # Sets the guest/host name for the previous put/get.
244 die "-a (or --as) is only allowed after -p or -g\n" if !defined $as_ref;
245 die "Only one -a (or --as) is allowed after -p or -g\n"
246 if defined $as_ref->[1];
250 # Sets $disk as a disk to be included in the VM to run.
254 push (@disks, $disk);
256 my (%pt) = read_partition_table ($disk);
257 for my $role (keys %pt) {
258 die "can't have two sources for \L$role\E partition"
259 if exists $parts{$role};
260 $parts{$role}{DISK} = $disk;
261 $parts{$role}{START} = $pt{$role}{START};
262 $parts{$role}{SECTORS} = $pt{$role}{SECTORS};
266 # Locates the files used to back each of the virtual disks,
267 # and creates temporary disks.
269 # Find kernel, if we don't already have one.
270 if (!exists $parts{KERNEL}) {
271 my $name = find_file ('kernel.bin');
272 die "Cannot find kernel\n" if !defined $name;
273 do_set_part ('KERNEL', 'file', $name);
276 # Try to find file system and swap disks, if we don't already have
278 if (!exists $parts{FILESYS}) {
279 my $name = find_file ('filesys.dsk');
280 set_disk ($name) if defined $name;
282 if (!exists $parts{SWAP}) {
283 my $name = find_file ('swap.dsk');
284 set_disk ($name) if defined $name;
287 # Warn about (potentially) missing partitions.
288 if (my ($project) = `pwd` =~ /\b(threads|userprog|vm|filesys)\b/) {
289 if ((grep ($project eq $_, qw (userprog vm filesys)))
290 && !defined $parts{FILESYS}) {
291 print STDERR "warning: it looks like you're running the $project ";
292 print STDERR "project, but no file system partition is present\n";
294 if ($project eq 'vm' && !defined $parts{SWAP}) {
295 print STDERR "warning: it looks like you're running the $project ";
296 print STDERR "project, but no swap partition is present\n";
302 if (!defined $make_disk) {
303 ($handle, $make_disk) = tempfile (UNLINK => $tmp_disk,
306 die "$make_disk: already exists\n" if -e $make_disk;
307 open ($handle, '>', $make_disk) or die "$make_disk: create: $!\n";
310 # Add "get" and "put" files to kernel args.
312 push (@args, shift (@kernel_args))
313 while @kernel_args && $kernel_args[0] =~ /^-/;
314 push (@args, 'extract') if @puts;
315 push (@args, @kernel_args);
316 push (@args, 'append', $_->[0]) foreach @gets;
321 for my $role (@role_order) {
322 my $p = $parts{$role};
324 next if exists $p->{DISK};
327 $disk{DISK} = $make_disk;
328 $disk{HANDLE} = $handle;
329 $disk{ALIGN} = $align;
330 $disk{GEOMETRY} = \%geometry;
331 $disk{FORMAT} = 'partitioned';
332 $disk{LOADER} = read_loader ($loader_fn);
333 $disk{ARGS} = \@args;
334 assemble_disk (%disk);
336 # Put the disk at the front of the list of disks.
337 unshift (@disks, $make_disk);
338 die "can't use more than " . scalar (@disks) . "disks\n" if @disks > 4;
341 # Prepare the scratch disk for gets and puts.
342 sub prepare_scratch_disk {
343 return if !@gets && !@puts;
345 my ($p) = $parts{SCRATCH};
347 # Create temporary partition and write the files to put to it.
348 my ($part_handle, $part_fn) = tempfile (UNLINK => 1, SUFFIX => '.part');
350 # Write ustar header and data for each file.
351 put_scratch_file ($_->[0],
352 defined $_->[1] ? $_->[1] : $_->[0],
353 $part_handle, $part_fn)
356 # Write end-of-archive marker.
357 print $part_handle "\0" x 1024;
360 # Make sure the scratch disk is big enough to get big files
361 # and at least as big as any requested size.
362 my ($size) = round_up (max (@gets * 1024 * 1024, $p->{BYTES} || 0), 512);
363 extend_file ($part_handle, $part_fn, $size);
364 close ($part_handle);
366 if (exists $p->{DISK}) {
367 # Copy the scratch partition to the disk.
368 die "$p->{DISK}: scratch partition too small\n"
369 if $p->{SECTORS} * 512 < $size;
372 open ($part_handle, '<', $part_fn) or die "$part_fn: open: $!\n";
373 open ($disk_handle, '+<', $p->{DISK}) or die "$p->{DISK}: open: $!\n";
374 my ($start) = $p->{START} * 512;
375 sysseek ($disk_handle, $start, SEEK_SET) == $start
376 or die "$p->{DISK}: seek: $!\n";
377 copy_file ($part_handle, $part_fn, $disk_handle, $p->{DISK}, $size);
378 close ($disk_handle) or die "$p->{DISK}: close: $!\n";
379 close ($part_handle) or die "$part_fn: close: $!\n";
381 # Set $part_fn as the source for the scratch partition.
382 do_set_part ('SCRATCH', 'file', $part_fn);
386 # Read "get" files from the scratch disk.
387 sub finish_scratch_disk {
388 return if !@gets || $sim eq 'hardware';
390 # Open scratch partition.
391 my ($p) = $parts{SCRATCH};
393 my ($part_fn) = $p->{DISK};
394 open ($part_handle, '<', $part_fn) or die "$part_fn: open: $!\n";
395 sysseek ($part_handle, $p->{START} * 512, SEEK_SET) == $p->{START} * 512
396 or die "$part_fn: seek: $!\n";
399 # If reading fails, delete that file and stop reading files.
401 my ($part_end) = ($p->{START} + $p->{SECTORS}) * 512;
402 foreach my $get (@gets) {
403 my ($name) = defined ($get->[1]) ? $get->[1] : $get->[0];
404 my ($error) = get_scratch_file ($name, $part_handle, $part_fn);
406 print STDERR "$part_fn: getting $name failed ($error)\n";
409 if (sysseek ($part_handle, 0, SEEK_CUR) > $part_end) {
411 print STDERR "$part_fn: scratch data overflows partition\n";
414 die "$name: unlink: $!\n" if !unlink ($name) && !$!{ENOENT};
420 # mk_ustar_field($number, $size)
422 # Returns $number in a $size-byte numeric field in the format used by
423 # the standard ustar archive header.
425 my ($number, $size) = @_;
426 my ($len) = $size - 1;
427 my ($out) = sprintf ("%0${len}o", $number) . "\0";
428 die "$number: too large for $size-byte octal ustar field\n"
429 if length ($out) != $size;
433 # calc_ustar_chksum($s)
435 # Calculates and returns the ustar checksum of 512-byte ustar archive
437 sub calc_ustar_chksum {
439 die if length ($s) != 512;
440 substr ($s, 148, 8, ' ' x 8);
441 return unpack ("%32a*", $s);
444 # put_scratch_file($src_file_name, $dst_file_name,
445 # $disk_handle, $disk_file_name).
447 # Copies $src_file_name into $disk_handle for extraction as
448 # $dst_file_name. $disk_file_name is used for error messages.
449 sub put_scratch_file {
450 my ($src_file_name, $dst_file_name, $disk_handle, $disk_file_name) = @_;
452 print "Copying $src_file_name to scratch partition...\n";
454 # ustar format supports up to 100 characters for a file name, and
455 # even longer names given some common properties, but our code in
456 # the Pintos kernel only supports at most 99 characters.
457 die "$dst_file_name: name too long (max 99 characters)\n"
458 if length ($dst_file_name) > 99;
460 # Compose and write ustar header.
461 stat $src_file_name or die "$src_file_name: stat: $!\n";
463 my ($header) = (pack ("a100", $dst_file_name) # name
464 . mk_ustar_field (0644, 8) # mode
465 . mk_ustar_field (0, 8) # uid
466 . mk_ustar_field (0, 8) # gid
467 . mk_ustar_field ($size, 12) # size
468 . mk_ustar_field (1136102400, 12) # mtime
471 . ("\0" x 100) # linkname
474 . "root" . ("\0" x 28) # uname
475 . "root" . ("\0" x 28) # gname
476 . "\0" x 8 # devmajor
477 . "\0" x 8 # devminor
478 . ("\0" x 155)) # prefix
479 . "\0" x 12; # pad to 512 bytes
480 substr ($header, 148, 8) = mk_ustar_field (calc_ustar_chksum ($header), 8);
481 write_fully ($disk_handle, $disk_file_name, $header);
485 sysopen ($put_handle, $src_file_name, O_RDONLY)
486 or die "$src_file_name: open: $!\n";
487 copy_file ($put_handle, $src_file_name, $disk_handle, $disk_file_name,
489 die "$src_file_name: changed size while being read\n"
490 if $size != -s $put_handle;
493 # Round up disk data to beginning of next sector.
494 write_fully ($disk_handle, $disk_file_name, "\0" x (512 - $size % 512))
498 # get_scratch_file($get_file_name, $disk_handle, $disk_file_name)
500 # Copies from $disk_handle to $get_file_name (which is created).
501 # $disk_file_name is used for error messages.
502 # Returns 1 if successful, 0 on failure.
503 sub get_scratch_file {
504 my ($get_file_name, $disk_handle, $disk_file_name) = @_;
506 print "Copying $get_file_name out of $disk_file_name...\n";
508 # Read ustar header sector.
509 my ($header) = read_fully ($disk_handle, $disk_file_name, 512);
510 return "scratch disk tar archive ends unexpectedly"
511 if $header eq ("\0" x 512);
513 # Verify magic numbers.
514 return "corrupt ustar signature" if substr ($header, 257, 6) ne "ustar\0";
515 return "invalid ustar version" if substr ($header, 263, 2) ne '00';
518 my ($chksum) = oct (unpack ("Z*", substr ($header, 148, 8)));
519 my ($correct_chksum) = calc_ustar_chksum ($header);
520 return "checksum mismatch" if $chksum != $correct_chksum;
523 my ($typeflag) = substr ($header, 156, 1);
524 return "not a regular file" if $typeflag ne '0' && $typeflag ne "\0";
527 my ($size) = oct (unpack ("Z*", substr ($header, 124, 12)));
528 return "bad size $size\n" if $size < 0;
532 sysopen ($get_handle, $get_file_name, O_WRONLY | O_CREAT, 0666)
533 or die "$get_file_name: create: $!\n";
534 copy_file ($disk_handle, $disk_file_name, $get_handle, $get_file_name,
538 # Skip forward in disk up to beginning of next sector.
539 read_fully ($disk_handle, $disk_file_name, 512 - $size % 512)
545 # Running simulators.
547 # Runs the selected simulator.
549 if ($sim eq 'bochs') {
551 } elsif ($sim eq 'qemu') {
553 } elsif ($sim eq 'player') {
555 } elsif ($sim eq 'hardware') {
556 print "Pintos disk image written to $make_disk.\n";
557 print "Copy this image to a physical disk for hardware boot.\n";
559 die "unknown simulator `$sim'\n";
565 # Select Bochs binary based on the chosen debugger.
566 my ($bin) = $debug eq 'monitor' ? 'bochs-dbg' : 'bochs';
570 $squish_pty = find_in_path ("squish-pty");
571 print "warning: can't find squish-pty, so terminal input will fail\n"
572 if !defined $squish_pty;
575 # Write bochsrc.txt configuration file.
576 open (BOCHSRC, ">", "bochsrc.txt") or die "bochsrc.txt: create: $!\n";
578 romimage: file=\$BXSHARE/BIOS-bochs-latest
579 vgaromimage: file=\$BXSHARE/VGABIOS-lgpl-latest
586 print BOCHSRC "gdbstub: enabled=1\n" if $debug eq 'gdb';
587 print BOCHSRC "clock: sync=", $realtime ? 'realtime' : 'none',
589 print BOCHSRC "ata1: enabled=1, ioaddr1=0x170, ioaddr2=0x370, irq=15\n"
591 print_bochs_disk_line ("ata0-master", $disks[0]);
592 print_bochs_disk_line ("ata0-slave", $disks[1]);
593 print_bochs_disk_line ("ata1-master", $disks[2]);
594 print_bochs_disk_line ("ata1-slave", $disks[3]);
595 if ($vga ne 'terminal') {
597 my $mode = defined ($squish_pty) ? "term" : "file";
598 print BOCHSRC "com1: enabled=1, mode=$mode, dev=/dev/stdout\n";
600 print BOCHSRC "display_library: nogui\n" if $vga eq 'none';
602 print BOCHSRC "display_library: term\n";
606 # Compose Bochs command line.
607 my (@cmd) = ($bin, '-q');
608 unshift (@cmd, $squish_pty) if defined $squish_pty;
609 push (@cmd, '-j', $jitter) if defined $jitter;
612 print join (' ', @cmd), "\n";
613 my ($exit) = xsystem (@cmd);
614 if (WIFEXITED ($exit)) {
615 # Bochs exited normally.
616 # Ignore the exit code; Bochs normally exits with status 1,
618 } elsif (WIFSIGNALED ($exit)) {
619 die "Bochs died with signal ", WTERMSIG ($exit), "\n";
621 die "Bochs died: code $exit\n";
625 sub print_bochs_disk_line {
626 my ($device, $disk) = @_;
628 my (%geom) = disk_geometry ($disk);
629 print BOCHSRC "$device: type=disk, path=$disk, mode=flat, ";
630 print BOCHSRC "cylinders=$geom{C}, heads=$geom{H}, spt=$geom{S}, ";
631 print BOCHSRC "translation=none\n";
637 print "warning: qemu doesn't support --terminal\n"
638 if $vga eq 'terminal';
639 print "warning: qemu doesn't support jitter\n"
641 my (@cmd) = ('qemu');
642 push (@cmd, '-no-kqemu');
644 push (@cmd, '-hda', $disks[0]) if defined $disks[0];
646 push (@cmd, '-usbdevice', "disk:$_") foreach @disks[1...$#disks];
648 push (@cmd, '-hda', $disks[0]) if defined $disks[0];
649 push (@cmd, '-hdb', $disks[1]) if defined $disks[1];
650 push (@cmd, '-hdc', $disks[2]) if defined $disks[2];
651 push (@cmd, '-hdd', $disks[3]) if defined $disks[3];
653 push (@cmd, '-m', $mem);
654 push (@cmd, '-net', 'none');
655 push (@cmd, '-nographic') if $vga eq 'none';
656 push (@cmd, '-serial', 'stdio') if $serial && $vga ne 'none';
657 push (@cmd, '-S') if $debug eq 'monitor';
658 push (@cmd, '-s', '-S') if $debug eq 'gdb';
659 push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none';
663 # player_unsup($flag)
665 # Prints a message that $flag is unsupported by VMware Player.
668 print "warning: no support for $flag with VMware Player\n";
671 # Runs VMware Player.
673 player_unsup ("--$debug") if $debug ne 'none';
674 player_unsup ("--no-vga") if $vga eq 'none';
675 player_unsup ("--terminal") if $vga eq 'terminal';
676 player_unsup ("--jitter") if defined $jitter;
677 player_unsup ("--timeout"), undef $timeout if defined $timeout;
678 player_unsup ("--kill-on-failure"), undef $kill_on_failure
679 if defined $kill_on_failure;
681 $mem = round_up ($mem, 4); # Memory must be multiple of 4 MB.
683 open (VMX, ">", "pintos.vmx") or die "pintos.vmx: create: $!\n";
684 chmod 0777 & ~umask, "pintos.vmx";
686 #! /usr/bin/vmware -G
690 floppy0.present = FALSE
692 sound.present = FALSE
693 gui.exitAtPowerOff = TRUE
694 gui.exitOnCLIHLT = TRUE
695 gui.powerOnAtStartUp = TRUE
696 usb.analyzer.enable = TRUE
700 loglevel.pci_uhci = 20
703 print VMX <<EOF if $serial;
704 serial0.present = TRUE
705 serial0.fileType = "pipe"
706 serial0.fileName = "pintos.socket"
707 serial0.pipe.endPoint = "client"
708 serial0.tryNoRxLoss = "TRUE"
711 for (my ($i) = 0; $i < 4; $i++) {
712 my ($dsk) = $disks[$i];
713 last if !defined $dsk;
715 my ($device) = "ide" . int ($i / 2) . ":" . ($i % 2);
716 my ($pln) = "$device.pln";
719 $device.present = TRUE
720 $device.deviceType = "plainDisk"
721 $device.fileName = "$pln"
724 open (URANDOM, '<', '/dev/urandom') or die "/dev/urandom: open: $!\n";
726 sysread (URANDOM, $bytes, 4) == 4 or die "/dev/urandom: read: $!\n";
728 my ($cid) = unpack ("L", $bytes);
730 my (%geom) = disk_geometry ($dsk);
731 open (PLN, ">", $pln) or die "$pln: create: $!\n";
736 createType="monolithicFlat"
738 RW $geom{CAPACITY} FLAT "$dsk" 0
743 ddb.adapterType = "ide"
744 ddb.virtualHWVersion = "4"
745 ddb.toolsVersion = "2"
746 ddb.geometry.cylinders = "$geom{C}"
747 ddb.geometry.heads = "$geom{H}"
748 ddb.geometry.sectors = "$geom{S}"
756 $squish_unix = find_in_path ("squish-unix");
757 print "warning: can't find squish-unix, so terminal input ",
758 "and output will fail\n" if !defined $squish_unix;
761 my ($vmx) = getcwd () . "/pintos.vmx";
762 my (@cmd) = ("vmware", $vmx);
763 unshift (@cmd, $squish_unix, "pintos.socket") if $squish_unix;
764 print join (' ', @cmd), "\n";
771 my ($handle, $file_name, $size) = @_;
772 if (-s ($handle) < $size) {
773 sysseek ($handle, $size - 1, 0) == $size - 1
774 or die "$file_name: seek: $!\n";
775 syswrite ($handle, "\0") == 1
776 or die "$file_name: write: $!\n";
780 # disk_geometry($file)
782 # Examines $file and returns a valid IDE disk geometry for it, as a
786 my ($size) = -s $file;
787 die "$file: stat: $!\n" if !defined $size;
788 die "$file: size $size not a multiple of 512 bytes\n" if $size % 512;
789 my ($cyl_size) = 512 * 16 * 63;
790 my ($cylinders) = ceil ($size / $cyl_size);
792 return (CAPACITY => $size / 512,
798 # Subprocess utilities.
802 # Runs xsystem(@args).
803 # Also prints the command it's running and checks that it succeeded.
805 print join (' ', @_), "\n";
806 die "command failed\n" if xsystem (@_);
811 # Creates a subprocess via exec(@args) and waits for it to complete.
812 # Relays common signals to the subprocess.
813 # If $timeout is set then the subprocess will be killed after that long.
815 # QEMU turns off local echo and does not restore it if killed by a signal.
816 # We compensate by restoring it ourselves.
817 my $cleanup = sub {};
819 my $termios = POSIX::Termios->new;
820 $termios->getattr (0);
821 $cleanup = sub { $termios->setattr (0, &POSIX::TCSANOW); }
824 # Create pipe for filtering output.
825 pipe (my $in, my $out) or die "pipe: $!\n" if $kill_on_failure;
828 if (!defined ($pid)) {
832 # Running in child process.
833 dup2 (fileno ($out), STDOUT_FILENO) or die "dup2: $!\n"
837 # Running in parent process.
838 close $out if $kill_on_failure;
841 local $SIG{ALRM} = sub { timeout ($pid, $cause, $cleanup); };
842 local $SIG{INT} = sub { relay_signal ($pid, "INT", $cleanup); };
843 local $SIG{TERM} = sub { relay_signal ($pid, "TERM", $cleanup); };
844 alarm ($timeout * get_load_average () + 1) if defined ($timeout);
846 if ($kill_on_failure) {
852 if (waitpid ($pid, WNOHANG) != 0) {
853 # Subprocess died. Pass through any remaining data.
854 print $buf while sysread ($in, $buf, 4096) > 0;
858 # Read and print out pipe data.
859 my ($len) = length ($buf);
860 waitpid ($pid, 0), last
861 if sysread ($in, $buf, 4096, $len) <= 0;
862 print substr ($buf, $len);
864 # Remove full lines from $buf and scan them for keywords.
865 while ((my $idx = index ($buf, "\n")) >= 0) {
866 local $_ = substr ($buf, 0, $idx + 1, '');
867 next if defined ($cause);
868 if (/(Kernel PANIC|User process ABORT)/ ) {
871 } elsif (/Pintos booting/ && ++$boots > 1) {
872 $cause = "triple fault";
875 $cause = "test failure";
886 if (WIFSIGNALED ($?) && WTERMSIG ($?) == SIGVTALRM ()) {
888 print "\nTIMEOUT after $timeout seconds of host CPU time\n";
896 # relay_signal($pid, $signal, &$cleanup)
898 # Relays $signal to $pid and then reinvokes it for us with the default
899 # handler. Also cleans up temporary files and invokes $cleanup.
901 my ($pid, $signal, $cleanup) = @_;
903 eval { File::Temp::cleanup() }; # Not defined in old File::Temp.
905 $SIG{$signal} = 'DEFAULT';
906 kill $signal, getpid ();
909 # timeout($pid, $cause, &$cleanup)
911 # Interrupts $pid and dies with a timeout error message,
912 # after invoking $cleanup.
914 my ($pid, $cause, $cleanup) = @_;
919 if (!defined ($cause)) {
920 my ($load_avg) = `uptime` =~ /(load average:.*)$/i;
921 print "\nTIMEOUT after ", time () - $start_time,
922 " seconds of wall-clock time";
923 print " - $load_avg" if defined $load_avg;
926 print "Simulation terminated due to $cause.\n";
931 # Returns the system load average over the last minute.
932 # If the load average is less than 1.0 or cannot be determined, returns 1.0.
933 sub get_load_average {
934 my ($avg) = `uptime` =~ /load average:\s*([^,]+),/;
935 return $avg >= 1.0 ? $avg : 1.0;
938 # Calls setitimer to set a timeout, then execs what was passed to us.
940 if (defined $timeout) {
943 use Time::HiRes qw(setitimer ITIMER_VIRTUAL);
944 setitimer (ITIMER_VIRTUAL, $timeout, 0);
947 { exec ("setitimer-helper", $timeout, @_); };
948 exit 1 if !$!{ENOENT};
949 print STDERR "warning: setitimer-helper is not installed, so ",
950 "CPU time limit will not be enforced\n";
960 foreach my $name (split(' ', $Config{sig_name})) {
961 return $i if $name eq 'VTALRM';
967 # find_in_path ($program)
969 # Searches for $program in $ENV{PATH}.
970 # Returns $program if found, otherwise undef.
973 -x "$_/$program" and return $program foreach split (':', $ENV{PATH});