provided code

This commit is contained in:
LabTS
2024-10-01 23:37:39 +01:00
commit 8724a2641e
697 changed files with 74252 additions and 0 deletions

3
src/utils/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
setitimer-helper
squish-pty
squish-unix

11
src/utils/Makefile Normal file
View File

@@ -0,0 +1,11 @@
all: setitimer-helper squish-pty squish-unix
CC = gcc
CFLAGS = -Wall -W
LDLIBS = -lm
setitimer-helper: setitimer-helper.o
squish-pty: squish-pty.o
squish-unix: squish-unix.o
clean:
rm -f *.o setitimer-helper squish-pty squish-unix

491
src/utils/Pintos.pm Normal file
View File

@@ -0,0 +1,491 @@
# PintOS helper subroutines.
# Number of bytes available for the loader at the beginning of the MBR.
# Kernel command-line arguments follow the loader.
our $LOADER_SIZE = 314;
# Partition types.
my (%role2type) = (KERNEL => 0x20,
FILESYS => 0x21,
SCRATCH => 0x22,
SWAP => 0x23);
my (%type2role) = reverse %role2type;
# Order of roles within a given disk.
our (@role_order) = qw (KERNEL FILESYS SCRATCH SWAP);
# Partitions.
#
# Valid keys are KERNEL, FILESYS, SCRATCH, SWAP. Only those
# partitions which are in use are included.
#
# Each value is a reference to a hash. If the partition's contents
# are to be obtained from a file (that will be copied into a new
# virtual disk), then the hash contains:
#
# FILE => name of file from which the partition's contents are copied
# (perhaps "/dev/zero"),
# OFFSET => offset in bytes in FILE,
# BYTES => size in bytes of contents from FILE,
#
# If the partition is taken from a virtual disk directly, then it
# contains the following. The same keys are also filled in once a
# file-based partition has been copied into a new virtual disk:
#
# DISK => name of virtual disk file,
# START => sector offset of start of partition within DISK,
# SECTORS => number of sectors of partition within DISK, which is usually
# greater than round_up (BYTES, 512) due to padding.
our (%parts);
# set_part($opt, $arg)
#
# For use as a helper function for Getopt::Long::GetOptions to set
# disk sources.
sub set_part {
my ($opt, $arg) = @_;
my ($role, $source) = $opt =~ /^([a-z]+)(?:-([a-z]+))?/ or die;
$role = uc $role;
$source = 'FILE' if $source eq '';
die "can't have two sources for \L$role\E partition"
if exists $parts{$role};
do_set_part ($role, $source, $arg);
}
# do_set_part($role, $source, $arg)
#
# Sets partition $role as coming from $source (one of 'file', 'from',
# or 'size'). $arg is a file name for 'file' or 'from', a size in
# megabytes for 'size'.
sub do_set_part {
my ($role, $source, $arg) = @_;
my ($p) = $parts{$role} = {};
if ($source eq 'file') {
if (read_mbr ($arg)) {
print STDERR "warning: $arg looks like a partitioned disk ";
print STDERR "(did you want --$role-from=$arg or --disk=$arg?)\n"
}
$p->{FILE} = $arg;
$p->{OFFSET} = 0;
$p->{BYTES} = -s $arg;
} elsif ($source eq 'from') {
my (%pt) = read_partition_table ($arg);
my ($sp) = $pt{$role};
die "$arg: does not contain \L$role\E partition\n" if !defined $sp;
$p->{FILE} = $arg;
$p->{OFFSET} = $sp->{START} * 512;
$p->{BYTES} = $sp->{SECTORS} * 512;
} elsif ($source eq 'size') {
$arg =~ /^\d+(\.\d+)?|\.\d+$/ or die "$arg: not a valid size in MB\n";
$p->{FILE} = "/dev/zero";
$p->{OFFSET} = 0;
$p->{BYTES} = ceil ($arg * 1024 * 1024);
} else {
die;
}
}
# set_geometry('HEADS,SPT')
# set_geometry('zip')
#
# For use as a helper function for Getopt::Long::GetOptions to set
# disk geometry.
sub set_geometry {
local ($_) = $_[1];
if ($_ eq 'zip') {
@geometry{'H', 'S'} = (64, 32);
} else {
@geometry{'H', 'S'} = /^(\d+)[,\s]+(\d+)$/
or die "bad syntax for geometry\n";
$geometry{H} <= 255 or die "heads limited to 255\n";
$geometry{S} <= 63 or die "sectors per track limited to 63\n";
}
}
# set_align('bochs|full|none')
#
# For use as a helper function for Getopt::Long::GetOptions to set
# partition alignment.
sub set_align {
$align = $_[1];
die "unknown alignment type \"$align\"\n"
if $align ne 'bochs' && $align ne 'full' && $align ne 'none';
}
# assemble_disk(%args)
#
# Creates a virtual disk $args{DISK} containing the partitions
# described by @args{KERNEL, FILESYS, SCRATCH, SWAP}.
#
# Required arguments:
# DISK => output disk file name
# HANDLE => output file handle (will be closed)
#
# Normally at least one of the following is included:
# KERNEL, FILESYS, SCRATCH, SWAP => {input:
# FILE => file to read,
# OFFSET => byte offset in file,
# BYTES => byte count from file,
#
# output:
# DISK => output disk file name,
# START => sector offset in DISK,
# SECTORS => sector count in DISK},
#
# Optional arguments:
# ALIGN => 'bochs' (default), 'full', or 'none'
# GEOMETRY => {H => heads, S => sectors per track} (default 16, 63)
# FORMAT => 'partitioned' (default) or 'raw'
# LOADER => $LOADER_SIZE-byte string containing the loader binary
# ARGS => ['arg 1', 'arg 2', ...]
sub assemble_disk {
my (%args) = @_;
my (%geometry) = $args{GEOMETRY} || (H => 16, S => 63);
my ($align); # Align partition start, end to cylinder boundary?
my ($pad); # Pad end of disk out to cylinder boundary?
if (!defined ($args{ALIGN}) || $args{ALIGN} eq 'bochs') {
$align = 0;
$pad = 1;
} elsif ($args{ALIGN} eq 'full') {
$align = 1;
$pad = 0;
} elsif ($args{ALIGN} eq 'none') {
$align = $pad = 0;
} else {
die;
}
my ($format) = $args{FORMAT} || 'partitioned';
die if $format ne 'partitioned' && $format ne 'raw';
# Check that we have apartitions to copy in.
my $part_cnt = grep (defined ($args{$_}), keys %role2type);
die "must have exactly one partition for raw output\n"
if $format eq 'raw' && $part_cnt != 1;
# Calculate the disk size.
my ($total_sectors) = 0;
if ($format eq 'partitioned') {
$total_sectors += $align ? $geometry{S} : 1;
}
for my $role (@role_order) {
my ($p) = $args{$role};
next if !defined $p;
die if $p->{DISK};
my ($bytes) = $p->{BYTES};
my ($start) = $total_sectors;
my ($end) = $start + div_round_up ($bytes, 512);
$end = round_up ($end, cyl_sectors (%geometry)) if $align;
$p->{DISK} = $args{DISK};
$p->{START} = $start;
$p->{SECTORS} = $end - $start;
$total_sectors = $end;
}
# Write the disk.
my ($disk_fn) = $args{DISK};
my ($disk) = $args{HANDLE};
if ($format eq 'partitioned') {
# Pack loader into MBR.
my ($loader) = $args{LOADER} || "\xcd\x18";
my ($mbr) = pack ("a$LOADER_SIZE", $loader);
$mbr .= make_kernel_command_line (@{$args{ARGS}});
# Pack partition table into MBR.
$mbr .= make_partition_table (\%geometry, \%args);
# Add signature to MBR.
$mbr .= pack ("v", 0xaa55);
die if length ($mbr) != 512;
write_fully ($disk, $disk_fn, $mbr);
write_zeros ($disk, $disk_fn, 512 * ($geometry{S} - 1)) if $align;
}
for my $role (@role_order) {
my ($p) = $args{$role};
next if !defined $p;
my ($source);
my ($fn) = $p->{FILE};
open ($source, '<', $fn) or die "$fn: open: $!\n";
if ($p->{OFFSET}) {
sysseek ($source, $p->{OFFSET}, 0) == $p->{OFFSET}
or die "$fn: seek: $!\n";
}
copy_file ($source, $fn, $disk, $disk_fn, $p->{BYTES});
close ($source) or die "$fn: close: $!\n";
write_zeros ($disk, $disk_fn, $p->{SECTORS} * 512 - $p->{BYTES});
}
if ($pad) {
my ($pad_sectors) = round_up ($total_sectors, cyl_sectors (%geometry));
write_zeros ($disk, $disk_fn, ($pad_sectors - $total_sectors) * 512);
}
close ($disk) or die "$disk: close: $!\n";
}
# make_partition_table({H => heads, S => sectors}, {KERNEL => ..., ...})
#
# Creates and returns a partition table for the given partitions and
# disk geometry.
sub make_partition_table {
my ($geometry, $partitions) = @_;
my ($table) = '';
for my $role (@role_order) {
defined (my $p = $partitions->{$role}) or next;
my $end = $p->{START} + $p->{SECTORS} - 1;
my $bootable = $role eq 'KERNEL';
$table .= pack ("C", $bootable ? 0x80 : 0); # Bootable?
$table .= pack_chs ($p->{START}, $geometry); # CHS of partition start
$table .= pack ("C", $role2type{$role}); # Partition type
$table .= pack_chs($end, $geometry); # CHS of partition end
$table .= pack ("V", $p->{START}); # LBA of partition start
$table .= pack ("V", $p->{SECTORS}); # Length in sectors
die if length ($table) % 16;
}
return pack ("a64", $table);
}
# make_kernel_command_line(@args)
#
# Returns the raw bytes to write to an MBR at offset $LOADER_SIZE to
# set a PintOS kernel command line.
sub make_kernel_command_line {
my (@args) = @_;
my ($args) = join ('', map ("$_\0", @args));
die "command line exceeds 128 bytes" if length ($args) > 128;
return pack ("V a128", scalar (@args), $args);
}
# copy_file($from_handle, $from_file_name, $to_handle, $to_file_name, $size)
#
# Copies $size bytes from $from_handle to $to_handle.
# $from_file_name and $to_file_name are used in error messages.
sub copy_file {
my ($from_handle, $from_file_name, $to_handle, $to_file_name, $size) = @_;
while ($size > 0) {
my ($chunk_size) = 4096;
$chunk_size = $size if $chunk_size > $size;
$size -= $chunk_size;
my ($data) = read_fully ($from_handle, $from_file_name, $chunk_size);
write_fully ($to_handle, $to_file_name, $data);
}
}
# read_fully($handle, $file_name, $bytes)
#
# Reads exactly $bytes bytes from $handle and returns the data read.
# $file_name is used in error messages.
sub read_fully {
my ($handle, $file_name, $bytes) = @_;
my ($data);
my ($read_bytes) = sysread ($handle, $data, $bytes);
die "$file_name: read: $!\n" if !defined $read_bytes;
die "$file_name: unexpected end of file\n" if $read_bytes != $bytes;
return $data;
}
# write_fully($handle, $file_name, $data)
#
# Write $data to $handle.
# $file_name is used in error messages.
sub write_fully {
my ($handle, $file_name, $data) = @_;
my ($written_bytes) = syswrite ($handle, $data);
die "$file_name: write: $!\n" if !defined $written_bytes;
die "$file_name: short write\n" if $written_bytes != length $data;
}
sub write_zeros {
my ($handle, $file_name, $size) = @_;
while ($size > 0) {
my ($chunk_size) = 4096;
$chunk_size = $size if $chunk_size > $size;
$size -= $chunk_size;
write_fully ($handle, $file_name, "\0" x $chunk_size);
}
}
# div_round_up($x,$y)
#
# Returns $x / $y, rounded up to the nearest integer.
# $y must be an integer.
sub div_round_up {
my ($x, $y) = @_;
return int ((ceil ($x) + $y - 1) / $y);
}
# round_up($x, $y)
#
# Returns $x rounded up to the nearest multiple of $y.
# $y must be an integer.
sub round_up {
my ($x, $y) = @_;
return div_round_up ($x, $y) * $y;
}
# cyl_sectors(H => heads, S => sectors)
#
# Returns the number of sectors in a cylinder of a disk with the given
# geometry.
sub cyl_sectors {
my (%geometry) = @_;
return $geometry{H} * $geometry{S};
}
# read_loader($file_name)
#
# Reads and returns the first $LOADER_SIZE bytes in $file_name.
# If $file_name is undefined, tries to find the default loader.
# Makes sure that the loader is a reasonable size.
sub read_loader {
my ($name) = @_;
$name = find_file ("loader.bin") if !defined $name;
die "Cannot find loader\n" if !defined $name;
my ($handle);
open ($handle, '<', $name) or die "$name: open: $!\n";
-s $handle == $LOADER_SIZE || -s $handle == 512
or die "$name: must be exactly $LOADER_SIZE or 512 bytes long\n";
$loader = read_fully ($handle, $name, $LOADER_SIZE);
close ($handle) or die "$name: close: $!\n";
return $loader;
}
# pack_chs($lba, {H => heads, S => sectors})
#
# Converts logical sector $lba to a 3-byte packed geometrical sector
# in the format used in PC partition tables (see [Partitions]) and
# returns the geometrical sector as a 3-byte string.
sub pack_chs {
my ($lba, $geometry) = @_;
my ($cyl, $head, $sect) = lba_to_chs ($lba, $geometry);
return pack ("CCC", $head, $sect | (($cyl >> 2) & 0xc0), $cyl & 0xff);
}
# lba_to_chs($lba, {H => heads, S => sectors})
#
# Returns the geometrical sector corresponding to logical sector $lba
# given the specified geometry.
sub lba_to_chs {
my ($lba, $geometry) = @_;
my ($hpc) = $geometry->{H};
my ($spt) = $geometry->{S};
# Source:
# http://en.wikipedia.org/wiki/CHS_conversion
use integer;
my $cyl = $lba / ($hpc * $spt);
my $temp = $lba % ($hpc * $spt);
my $head = $temp / $spt;
my $sect = $temp % $spt + 1;
# Source:
# http://www.cgsecurity.org/wiki/Intel_Partition_Table
if ($cyl <= 1023) {
return ($cyl, $head, $sect);
} else {
return (1023, 254, 63); ## or should this be (1023, $hpc, $spt)?
}
}
# read_mbr($file)
#
# Tries to read an MBR from $file. Returns the 512-byte MBR if
# successful, otherwise numeric 0.
sub read_mbr {
my ($file) = @_;
my ($retval) = 0;
open (FILE, '<', $file) or die "$file: open: $!\n";
if (-s FILE == 0) {
die "$file: file has zero size\n";
} elsif (-s FILE >= 512) {
my ($mbr);
sysread (FILE, $mbr, 512) == 512 or die "$file: read: $!\n";
$retval = $mbr if unpack ("v", substr ($mbr, 510)) == 0xaa55;
}
close (FILE);
return $retval;
}
# interpret_partition_table($mbr, $disk)
#
# Parses the partition-table in the specified 512-byte $mbr and
# returns the partitions. $disk is used for error messages.
sub interpret_partition_table {
my ($mbr, $disk) = @_;
my (%parts);
for my $i (0...3) {
my ($bootable, $valid, $type, $lba_start, $lba_length)
= unpack ("C X V C x3 V V", substr ($mbr, 446 + 16 * $i, 16));
next if !$valid;
(print STDERR "warning: invalid partition entry $i in $disk\n"),
next if $bootable != 0 && $bootable != 0x80;
my ($role) = $type2role{$type};
(printf STDERR "warning: non-PintOS partition type 0x%02x in %s\n",
$type, $disk),
next if !defined $role;
(print STDERR "warning: duplicate \L$role\E partition in $disk\n"),
next if exists $parts{$role};
$parts{$role} = {START => $lba_start,
SECTORS => $lba_length};
}
return %parts;
}
# find_file($base_name)
#
# Looks for a file named $base_name in a couple of likely spots. If
# found, returns the name; otherwise, returns undef.
sub find_file {
my ($base_name) = @_;
-e && return $_ foreach $base_name, "build/$base_name";
return undef;
}
# read_partition_table($file)
#
# Reads a partition table from $file and returns the parsed
# partitions. Dies if partitions can't be read.
sub read_partition_table {
my ($file) = @_;
my ($mbr) = read_mbr ($file);
die "$file: not a partitioned disk\n" if !$mbr;
return interpret_partition_table ($mbr, $file);
}
# max(@args)
#
# Returns the numerically largest value in @args.
sub max {
my ($max) = $_[0];
foreach (@_[1..$#_]) {
$max = $_ if $_ > $max;
}
return $max;
}
1;

106
src/utils/backtrace Executable file
View File

@@ -0,0 +1,106 @@
#! /usr/bin/perl -w
use strict;
# Check command line.
if (grep ($_ eq '-h' || $_ eq '--help', @ARGV)) {
print <<'EOF';
backtrace, for converting raw addresses into symbolic backtraces
usage: backtrace [BINARY]... ADDRESS...
where BINARY is the binary file or files from which to obtain symbols
and ADDRESS is a raw address to convert to a symbol name.
If no BINARY is unspecified, the default is the first of kernel.o or
build/kernel.o that exists. If multiple binaries are specified, each
symbol printed is from the first binary that contains a match.
The ADDRESS list should be taken from the "Call stack:" printed by the
kernel. Read "Backtraces" in the "Debugging Tools" chapter of the
PintOS documentation for more information.
EOF
exit 0;
}
die "backtrace: at least one argument required (use --help for help)\n"
if @ARGV == 0;
# Drop garbage inserted by kernel.
@ARGV = grep (!/^(call|stack:?|[-+])$/i, @ARGV);
s/\.$// foreach @ARGV;
# Find binaries.
my (@binaries);
while ($ARGV[0] !~ /^0x/) {
my ($bin) = shift @ARGV;
die "backtrace: $bin: not found (use --help for help)\n" if ! -e $bin;
push (@binaries, $bin);
}
if (!@binaries) {
my ($bin);
if (-e 'kernel.o') {
$bin = 'kernel.o';
} elsif (-e 'build/kernel.o') {
$bin = 'build/kernel.o';
} else {
die "backtrace: no binary specified and neither \"kernel.o\" nor \"build/kernel.o\" exists (use --help for help)\n";
}
push (@binaries, $bin);
}
# Find addr2line.
my ($a2l) = search_path ("i686-elf-addr2line") || search_path ("addr2line");
if (!$a2l) {
die "backtrace: neither `i686-elf-addr2line' nor `addr2line' in PATH\n";
}
sub search_path {
my ($target) = @_;
for my $dir (split (':', $ENV{PATH})) {
my ($file) = "$dir/$target";
return $file if -e $file;
}
return undef;
}
# Figure out backtrace.
my (@locs) = map ({ADDR => $_}, @ARGV);
for my $bin (@binaries) {
open (A2L, "$a2l -fe $bin " . join (' ', map ($_->{ADDR}, @locs)) . "|");
for (my ($i) = 0; <A2L>; $i++) {
my ($function, $line);
chomp ($function = $_);
chomp ($line = <A2L>);
next if defined $locs[$i]{BINARY};
if ($function ne '??' || $line ne '??:0') {
$locs[$i]{FUNCTION} = $function;
$locs[$i]{LINE} = $line;
$locs[$i]{BINARY} = $bin;
}
}
close (A2L);
}
# Print backtrace.
my ($cur_binary);
for my $loc (@locs) {
if (defined ($loc->{BINARY})
&& @binaries > 1
&& (!defined ($cur_binary) || $loc->{BINARY} ne $cur_binary)) {
$cur_binary = $loc->{BINARY};
print "In $cur_binary:\n";
}
my ($addr) = $loc->{ADDR};
$addr = sprintf ("0x%08x", hex ($addr)) if $addr =~ /^0x[0-9a-f]+$/i;
print $addr, ": ";
if (defined ($loc->{BINARY})) {
my ($function) = $loc->{FUNCTION};
my ($line) = $loc->{LINE};
$line =~ s/^(\.\.\/)*//;
$line = "..." . substr ($line, -25) if length ($line) > 28;
print "$function ($line)";
} else {
print "(unknown)";
}
print "\n";
}

947
src/utils/pintos Executable file
View File

@@ -0,0 +1,947 @@
#! /usr/bin/perl -w
use strict;
use POSIX;
use Fcntl;
use File::Temp 'tempfile';
use Getopt::Long qw(:config bundling);
use Fcntl qw(SEEK_SET SEEK_CUR);
# Read Pintos.pm from the same directory as this program.
BEGIN { my $self = $0; $self =~ s%/+[^/]*$%%; require "$self/Pintos.pm"; }
# Command-line options.
our ($start_time) = time ();
our ($sim); # Simulator: bochs, qemu, or player.
our ($debug) = "none"; # Debugger: none, monitor, or gdb.
our ($mem) = 4; # Physical RAM in MB.
our ($serial) = 1; # Use serial port for input and output?
our ($vga); # VGA output: window, terminal, or none.
our ($jitter); # Seed for random timer interrupts, if set.
our ($realtime); # Synchronize timer interrupts with real time?
our ($timeout); # Maximum runtime in seconds, if set.
our ($kill_on_failure); # Abort quickly on test failure?
our (@puts); # Files to copy into the VM.
our (@gets); # Files to copy out of the VM.
our ($as_ref); # Reference to last addition to @gets or @puts.
our (@kernel_args); # Arguments to pass to kernel.
our (%parts); # Partitions.
our ($make_disk); # Name of disk to create.
our ($tmp_disk) = 1; # Delete $make_disk after run?
our (@disks); # Extra disk images to pass to simulator.
our ($loader_fn); # Bootstrap loader.
our (%geometry); # IDE disk geometry.
our ($align); # Partition alignment.
parse_command_line ();
prepare_scratch_disk ();
find_disks ();
run_vm ();
finish_scratch_disk ();
exit 0;
# Parses the command line.
sub parse_command_line {
usage (0) if @ARGV == 0 || (@ARGV == 1 && $ARGV[0] eq '--help');
@kernel_args = @ARGV;
if (grep ($_ eq '--', @kernel_args)) {
@ARGV = ();
while ((my $arg = shift (@kernel_args)) ne '--') {
push (@ARGV, $arg);
}
GetOptions ("sim=s" => sub { set_sim ($_[1]) },
"bochs" => sub { set_sim ("bochs") },
"qemu" => sub { set_sim ("qemu") },
"player" => sub { set_sim ("player") },
"debug=s" => sub { set_debug ($_[1]) },
"no-debug" => sub { set_debug ("none") },
"monitor" => sub { set_debug ("monitor") },
"gdb" => sub { set_debug ("gdb") },
"m|memory=i" => \$mem,
"j|jitter=i" => sub { set_jitter ($_[1]) },
"r|realtime" => sub { set_realtime () },
"T|timeout=i" => \$timeout,
"k|kill-on-failure" => \$kill_on_failure,
"v|no-vga" => sub { set_vga ('none'); },
"s|no-serial" => sub { $serial = 0; },
"t|terminal" => sub { set_vga ('terminal'); },
"p|put-file=s" => sub { add_file (\@puts, $_[1]); },
"g|get-file=s" => sub { add_file (\@gets, $_[1]); },
"a|as=s" => sub { set_as ($_[1]); },
"h|help" => sub { usage (0); },
"kernel=s" => \&set_part,
"filesys=s" => \&set_part,
"swap=s" => \&set_part,
"filesys-size=s" => \&set_part,
"scratch-size=s" => \&set_part,
"swap-size=s" => \&set_part,
"kernel-from=s" => \&set_part,
"filesys-from=s" => \&set_part,
"swap-from=s" => \&set_part,
"make-disk=s" => sub { $make_disk = $_[1];
$tmp_disk = 0; },
"disk=s" => sub { set_disk ($_[1]); },
"loader=s" => \$loader_fn,
"geometry=s" => \&set_geometry,
"align=s" => \&set_align)
or exit 1;
}
$sim = "qemu" if !defined $sim;
$debug = "none" if !defined $debug;
$vga = exists ($ENV{DISPLAY}) ? "window" : "none" if !defined $vga;
undef $timeout, print "warning: disabling timeout with --$debug\n"
if defined ($timeout) && $debug ne 'none';
print "warning: enabling serial port for -k or --kill-on-failure\n"
if $kill_on_failure && !$serial;
$align = "bochs",
print STDERR "warning: setting --align=bochs for Bochs support\n"
if $sim eq 'bochs' && defined ($align) && $align eq 'none';
}
# usage($exitcode).
# Prints a usage message and exits with $exitcode.
sub usage {
my ($exitcode) = @_;
$exitcode = 1 unless defined $exitcode;
print <<'EOF';
pintos, a utility for running PintOS in a simulator
Usage: pintos [OPTION...] -- [ARGUMENT...]
where each OPTION is one of the following options
and each ARGUMENT is passed to PintOS kernel verbatim.
Simulator selection:
--qemu (default) Use QEMU as simulator
--bochs Use Bochs as simulator
--player Use VMware Player as simulator
Debugger selection:
--no-debug (default) No debugger
--monitor Debug with simulator's monitor
--gdb Debug with gdb
Display options: (default is both VGA and serial)
-v, --no-vga No VGA display or keyboard
-s, --no-serial No serial input or output
-t, --terminal Display VGA in terminal (Bochs only)
Timing options: (Bochs only)
-j SEED Randomize timer interrupts
-r, --realtime Use realistic, not reproducible, timings
Testing options:
-T, --timeout=N Kill PintOS after N seconds CPU time or N*load_avg
seconds wall-clock time (whichever comes first)
-k, --kill-on-failure Kill PintOS a few seconds after a kernel or user
panic, test failure, or triple fault
Configuration options:
-m, --mem=N Give PintOS N MB physical RAM (default: 4)
File system commands:
-p, --put-file=HOSTFN Copy HOSTFN into VM, by default under same name
-g, --get-file=GUESTFN Copy GUESTFN out of VM, by default under same name
-a, --as=FILENAME Specifies guest (for -p) or host (for -g) file name
Partition options: (where PARTITION is one of: kernel filesys scratch swap)
--PARTITION=FILE Use a copy of FILE for the given PARTITION
--PARTITION-size=SIZE Create an empty PARTITION of the given SIZE in MB
--PARTITION-from=DISK Use of a copy of the given PARTITION in DISK
(There is no --kernel-size, --scratch, or --scratch-from option.)
Disk configuration options:
--make-disk=DISK Name the new DISK and don't delete it after the run
--disk=DISK Also use existing DISK (may be used multiple times)
Advanced disk configuration options:
--loader=FILE Use FILE as bootstrap loader (default: loader.bin)
--geometry=H,S Use H head, S sector geometry (default: 16,63)
--geometry=zip Use 64 head, 32 sector geometry for USB-ZIP boot
(see http://syslinux.zytor.com/usbkey.php)
--align=bochs Pad out disk to cylinder to support Bochs (default)
--align=full Align partition boundaries to cylinder boundary to
let fdisk guess correct geometry and quiet warnings
--align=none Don't align partitions at all, to save space
Other options:
-h, --help Display this help message.
EOF
exit $exitcode;
}
# Sets the simulator.
sub set_sim {
my ($new_sim) = @_;
die "--$new_sim conflicts with --$sim\n"
if defined ($sim) && $sim ne $new_sim;
$sim = $new_sim;
}
# Sets the debugger.
sub set_debug {
my ($new_debug) = @_;
die "--$new_debug conflicts with --$debug\n"
if $debug ne 'none' && $new_debug ne 'none' && $debug ne $new_debug;
$debug = $new_debug;
}
# Sets VGA output destination.
sub set_vga {
my ($new_vga) = @_;
if (defined ($vga) && $vga ne $new_vga) {
print "warning: conflicting vga display options\n";
}
$vga = $new_vga;
}
# Sets randomized timer interrupts.
sub set_jitter {
my ($new_jitter) = @_;
die "--realtime conflicts with --jitter\n" if defined $realtime;
die "different --jitter already defined\n"
if defined $jitter && $jitter != $new_jitter;
$jitter = $new_jitter;
}
# Sets real-time timer interrupts.
sub set_realtime {
die "--realtime conflicts with --jitter\n" if defined $jitter;
$realtime = 1;
}
# add_file(\@list, $file)
#
# Adds [$file] to @list, which should be @puts or @gets.
# Sets $as_ref to point to the added element.
sub add_file {
my ($list, $file) = @_;
$as_ref = [$file];
push (@$list, $as_ref);
}
# Sets the guest/host name for the previous put/get.
sub set_as {
my ($as) = @_;
die "-a (or --as) is only allowed after -p or -g\n" if !defined $as_ref;
die "Only one -a (or --as) is allowed after -p or -g\n"
if defined $as_ref->[1];
$as_ref->[1] = $as;
}
# Sets $disk as a disk to be included in the VM to run.
sub set_disk {
my ($disk) = @_;
push (@disks, $disk);
my (%pt) = read_partition_table ($disk);
for my $role (keys %pt) {
die "can't have two sources for \L$role\E partition"
if exists $parts{$role};
$parts{$role}{DISK} = $disk;
$parts{$role}{START} = $pt{$role}{START};
$parts{$role}{SECTORS} = $pt{$role}{SECTORS};
}
}
# Locates the files used to back each of the virtual disks,
# and creates temporary disks.
sub find_disks {
# Find kernel, if we don't already have one.
if (!exists $parts{KERNEL}) {
my $name = find_file ('kernel.bin');
die "Cannot find kernel\n" if !defined $name;
do_set_part ('KERNEL', 'file', $name);
}
# Try to find file system and swap disks, if we don't already have
# partitions.
if (!exists $parts{FILESYS}) {
my $name = find_file ('filesys.dsk');
set_disk ($name) if defined $name;
}
if (!exists $parts{SWAP}) {
my $name = find_file ('swap.dsk');
set_disk ($name) if defined $name;
}
# Warn about (potentially) missing partitions.
if (my ($task) = `pwd` =~ /\b(threads|userprog|vm|filesys)\b/) {
if ((grep ($task eq $_, qw (userprog vm filesys)))
&& !defined $parts{FILESYS}) {
print STDERR "warning: it looks like you're running the $task ";
print STDERR "task, but no file system partition is present\n";
}
if ($task eq 'vm' && !defined $parts{SWAP}) {
print STDERR "warning: it looks like you're running the $task ";
print STDERR "task, but no swap partition is present\n";
}
}
# Open disk handle.
my ($handle);
if (!defined $make_disk) {
($handle, $make_disk) = tempfile (UNLINK => $tmp_disk,
SUFFIX => '.dsk');
} else {
die "$make_disk: already exists\n" if -e $make_disk;
open ($handle, '>', $make_disk) or die "$make_disk: create: $!\n";
}
# Prepare the arguments to pass to the PintOS kernel.
my (@args);
push (@args, shift (@kernel_args))
while @kernel_args && $kernel_args[0] =~ /^-/;
push (@args, 'extract') if @puts;
push (@args, @kernel_args);
push (@args, 'append', $_->[0]) foreach @gets;
# Make disk.
my (%disk);
our (@role_order);
for my $role (@role_order) {
my $p = $parts{$role};
next if !defined $p;
next if exists $p->{DISK};
$disk{$role} = $p;
}
$disk{DISK} = $make_disk;
$disk{HANDLE} = $handle;
$disk{ALIGN} = $align;
$disk{GEOMETRY} = %geometry;
$disk{FORMAT} = 'partitioned';
$disk{LOADER} = read_loader ($loader_fn);
$disk{ARGS} = \@args;
assemble_disk (%disk);
# Put the disk at the front of the list of disks.
unshift (@disks, $make_disk);
die "can't use more than " . scalar (@disks) . "disks\n" if @disks > 4;
}
# Prepare the scratch disk for gets and puts.
sub prepare_scratch_disk {
return if !@gets && !@puts;
my ($p) = $parts{SCRATCH};
# Create temporary partition and write the files to put to it,
# then write an end-of-archive marker.
my ($part_handle, $part_fn) = tempfile (UNLINK => 1, SUFFIX => '.part');
put_scratch_file ($_->[0], defined $_->[1] ? $_->[1] : $_->[0],
$part_handle, $part_fn)
foreach @puts;
write_fully ($part_handle, $part_fn, "\0" x 1024);
# Make sure the scratch disk is big enough to get big files
# and at least as big as any requested size.
my ($size) = round_up (max (@gets * 1024 * 1024, $p->{BYTES} || 0), 512);
extend_file ($part_handle, $part_fn, $size);
close ($part_handle);
if (exists $p->{DISK}) {
# Copy the scratch partition to the disk.
die "$p->{DISK}: scratch partition too small\n"
if $p->{SECTORS} * 512 < $size;
my ($disk_handle);
open ($part_handle, '<', $part_fn) or die "$part_fn: open: $!\n";
open ($disk_handle, '+<', $p->{DISK}) or die "$p->{DISK}: open: $!\n";
my ($start) = $p->{START} * 512;
sysseek ($disk_handle, $start, SEEK_SET) == $start
or die "$p->{DISK}: seek: $!\n";
copy_file ($part_handle, $part_fn, $disk_handle, $p->{DISK}, $size);
close ($disk_handle) or die "$p->{DISK}: close: $!\n";
close ($part_handle) or die "$part_fn: close: $!\n";
} else {
# Set $part_fn as the source for the scratch partition.
do_set_part ('SCRATCH', 'file', $part_fn);
}
}
# Read "get" files from the scratch disk.
sub finish_scratch_disk {
return if !@gets;
# Open scratch partition.
my ($p) = $parts{SCRATCH};
my ($part_handle);
my ($part_fn) = $p->{DISK};
open ($part_handle, '<', $part_fn) or die "$part_fn: open: $!\n";
sysseek ($part_handle, $p->{START} * 512, SEEK_SET) == $p->{START} * 512
or die "$part_fn: seek: $!\n";
# Read each file.
# If reading fails, delete that file and all subsequent files, but
# don't die with an error, because that's a guest error not a host
# error. (If we do exit with an error code, it fouls up the
# grading process.) Instead, just make sure that the host file(s)
# we were supposed to retrieve is unlinked.
my ($ok) = 1;
my ($part_end) = ($p->{START} + $p->{SECTORS}) * 512;
foreach my $get (@gets) {
my ($name) = defined ($get->[1]) ? $get->[1] : $get->[0];
if ($ok) {
my ($error) = get_scratch_file ($name, $part_handle, $part_fn);
if (!$error && sysseek ($part_handle, 0, SEEK_CUR) > $part_end) {
$error = "$part_fn: scratch data overflows partition";
}
if ($error) {
print STDERR "getting $name failed ($error)\n";
$ok = 0;
}
}
die "$name: unlink: $!\n" if !$ok && !unlink ($name) && !$!{ENOENT};
}
}
# mk_ustar_field($number, $size)
#
# Returns $number in a $size-byte numeric field in the format used by
# the standard ustar archive header.
sub mk_ustar_field {
my ($number, $size) = @_;
my ($len) = $size - 1;
my ($out) = sprintf ("%0${len}o", $number) . "\0";
die "$number: too large for $size-byte octal ustar field\n"
if length ($out) != $size;
return $out;
}
# calc_ustar_chksum($s)
#
# Calculates and returns the ustar checksum of 512-byte ustar archive
# header $s.
sub calc_ustar_chksum {
my ($s) = @_;
die if length ($s) != 512;
substr ($s, 148, 8, ' ' x 8);
return unpack ("%32a*", $s);
}
# put_scratch_file($src_file_name, $dst_file_name,
# $disk_handle, $disk_file_name).
#
# Copies $src_file_name into $disk_handle for extraction as
# $dst_file_name. $disk_file_name is used for error messages.
sub put_scratch_file {
my ($src_file_name, $dst_file_name, $disk_handle, $disk_file_name) = @_;
print "Copying $src_file_name to scratch partition...\n";
# ustar format supports up to 100 characters for a file name, and
# even longer names given some common properties, but our code in
# the PintOS kernel only supports at most 99 characters.
die "$dst_file_name: name too long (max 99 characters)\n"
if length ($dst_file_name) > 99;
# Compose and write ustar header.
stat $src_file_name or die "$src_file_name: stat: $!\n";
my ($size) = -s _;
my ($header) = (pack ("a100", $dst_file_name) # name
. mk_ustar_field (0644, 8) # mode
. mk_ustar_field (0, 8) # uid
. mk_ustar_field (0, 8) # gid
. mk_ustar_field ($size, 12) # size
. mk_ustar_field (1136102400, 12) # mtime
. (' ' x 8) # chksum
. '0' # typeflag
. ("\0" x 100) # linkname
. "ustar\0" # magic
. "00" # version
. "root" . ("\0" x 28) # uname
. "root" . ("\0" x 28) # gname
. "\0" x 8 # devmajor
. "\0" x 8 # devminor
. ("\0" x 155)) # prefix
. "\0" x 12; # pad to 512 bytes
substr ($header, 148, 8) = mk_ustar_field (calc_ustar_chksum ($header), 8);
write_fully ($disk_handle, $disk_file_name, $header);
# Copy file data.
my ($put_handle);
sysopen ($put_handle, $src_file_name, O_RDONLY)
or die "$src_file_name: open: $!\n";
copy_file ($put_handle, $src_file_name, $disk_handle, $disk_file_name,
$size);
die "$src_file_name: changed size while being read\n"
if $size != -s $put_handle;
close ($put_handle);
# Round up disk data to beginning of next sector.
write_fully ($disk_handle, $disk_file_name, "\0" x (512 - $size % 512))
if $size % 512;
}
# get_scratch_file($get_file_name, $disk_handle, $disk_file_name)
#
# Copies from $disk_handle to $get_file_name (which is created).
# $disk_file_name is used for error messages.
# Returns 1 if successful, 0 on failure.
sub get_scratch_file {
my ($get_file_name, $disk_handle, $disk_file_name) = @_;
print "Copying $get_file_name out of $disk_file_name...\n";
# Read ustar header sector.
my ($header) = read_fully ($disk_handle, $disk_file_name, 512);
return "scratch disk tar archive ends unexpectedly"
if $header eq ("\0" x 512);
# Verify magic numbers.
return "corrupt ustar signature" if substr ($header, 257, 6) ne "ustar\0";
return "invalid ustar version" if substr ($header, 263, 2) ne '00';
# Verify checksum.
my ($chksum) = oct (unpack ("Z*", substr ($header, 148, 8)));
my ($correct_chksum) = calc_ustar_chksum ($header);
return "checksum mismatch" if $chksum != $correct_chksum;
# Get type.
my ($typeflag) = substr ($header, 156, 1);
return "not a regular file" if $typeflag ne '0' && $typeflag ne "\0";
# Get size.
my ($size) = oct (unpack ("Z*", substr ($header, 124, 12)));
return "bad size $size\n" if $size < 0;
# Copy file data.
my ($get_handle);
sysopen ($get_handle, $get_file_name, O_WRONLY | O_CREAT, 0666)
or die "$get_file_name: create: $!\n";
copy_file ($disk_handle, $disk_file_name, $get_handle, $get_file_name,
$size);
close ($get_handle);
# Skip forward in disk up to beginning of next sector.
read_fully ($disk_handle, $disk_file_name, 512 - $size % 512)
if $size % 512;
return 0;
}
# Running simulators.
# Runs the selected simulator.
sub run_vm {
if ($sim eq 'bochs') {
run_bochs ();
} elsif ($sim eq 'qemu') {
run_qemu ();
} elsif ($sim eq 'player') {
run_player ();
} else {
die "unknown simulator `$sim'\n";
}
}
# Runs Bochs.
sub run_bochs {
# Select Bochs binary based on the chosen debugger.
my ($bin) = $debug eq 'monitor' ? 'bochs-dbg' : 'bochs';
my ($squish_pty);
if ($serial) {
$squish_pty = find_in_path ("squish-pty");
print "warning: can't find squish-pty, so terminal input will fail\n"
if !defined $squish_pty;
}
# Write bochsrc.txt configuration file.
open (BOCHSRC, ">", "bochsrc.txt") or die "bochsrc.txt: create: $!\n";
print BOCHSRC <<EOF;
romimage: file=\$BXSHARE/BIOS-bochs-latest
vgaromimage: file=\$BXSHARE/VGABIOS-lgpl-latest
boot: disk
cpu: ips=1000000
megs: $mem
log: bochsout.txt
panic: action=fatal
user_shortcut: keys=ctrlaltdel
EOF
print BOCHSRC "gdbstub: enabled=1\n" if $debug eq 'gdb';
print BOCHSRC "clock: sync=", $realtime ? 'realtime' : 'none',
", time0=0\n";
print BOCHSRC "ata1: enabled=1, ioaddr1=0x170, ioaddr2=0x370, irq=15\n"
if @disks > 2;
print_bochs_disk_line ("ata0-master", $disks[0]);
print_bochs_disk_line ("ata0-slave", $disks[1]);
print_bochs_disk_line ("ata1-master", $disks[2]);
print_bochs_disk_line ("ata1-slave", $disks[3]);
if ($vga ne 'terminal') {
if ($serial) {
my $mode = defined ($squish_pty) ? "term" : "file";
print BOCHSRC "com1: enabled=1, mode=$mode, dev=/dev/stdout\n";
}
print BOCHSRC "display_library: nogui\n" if $vga eq 'none';
} else {
print BOCHSRC "display_library: term\n";
}
close (BOCHSRC);
# Compose Bochs command line.
my (@cmd) = ($bin, '-q');
unshift (@cmd, $squish_pty) if defined $squish_pty;
push (@cmd, '-j', $jitter) if defined $jitter;
# Run Bochs.
print join (' ', @cmd), "\n";
my ($exit) = xsystem (@cmd);
if (WIFEXITED ($exit)) {
# Bochs exited normally.
# Ignore the exit code; Bochs normally exits with status 1,
# which is weird.
} elsif (WIFSIGNALED ($exit)) {
die "Bochs died with signal ", WTERMSIG ($exit), "\n";
} else {
die "Bochs died: code $exit\n";
}
}
sub print_bochs_disk_line {
my ($device, $disk) = @_;
if (defined $disk) {
my (%geom) = disk_geometry ($disk);
print BOCHSRC "$device: type=disk, path=$disk, mode=flat, ";
print BOCHSRC "cylinders=$geom{C}, heads=$geom{H}, spt=$geom{S}, ";
print BOCHSRC "translation=none\n";
}
}
# Runs QEMU.
sub run_qemu {
print "warning: qemu doesn't support --terminal\n"
if $vga eq 'terminal';
print "warning: qemu doesn't support jitter\n"
if defined $jitter;
my (@cmd) = ('qemu-system-i386');
push (@cmd, '-drive', 'file='.$disks[0].',index=0,media=disk,format=raw') if defined $disks[0];
push (@cmd, '-drive', 'file='.$disks[1].',index=1,media=disk,format=raw') if defined $disks[1];
push (@cmd, '-drive', 'file='.$disks[2].',index=2,media=disk,format=raw') if defined $disks[2];
push (@cmd, '-drive', 'file='.$disks[3].',index=3,media=disk,format=raw') if defined $disks[3];
push (@cmd, '-m', $mem);
push (@cmd, '-net', 'none');
push (@cmd, '-nographic') if $vga eq 'none';
push (@cmd, '-serial', 'stdio') if $serial && $vga ne 'none';
push (@cmd, '-S') if $debug eq 'monitor';
push (@cmd, '-s', '-S') if $debug eq 'gdb';
push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none';
run_command (@cmd);
}
# player_unsup($flag)
#
# Prints a message that $flag is unsupported by VMware Player.
sub player_unsup {
my ($flag) = @_;
print "warning: no support for $flag with VMware Player\n";
}
# Runs VMware Player.
sub run_player {
player_unsup ("--$debug") if $debug ne 'none';
player_unsup ("--no-vga") if $vga eq 'none';
player_unsup ("--terminal") if $vga eq 'terminal';
player_unsup ("--jitter") if defined $jitter;
player_unsup ("--timeout"), undef $timeout if defined $timeout;
player_unsup ("--kill-on-failure"), undef $kill_on_failure
if defined $kill_on_failure;
$mem = round_up ($mem, 4); # Memory must be multiple of 4 MB.
open (VMX, ">", "pintos.vmx") or die "pintos.vmx: create: $!\n";
chmod 0777 & ~umask, "pintos.vmx";
print VMX <<EOF;
#! /usr/bin/vmware -G
config.version = 8
guestOS = "linux"
memsize = $mem
floppy0.present = FALSE
usb.present = FALSE
sound.present = FALSE
gui.exitAtPowerOff = TRUE
gui.exitOnCLIHLT = TRUE
gui.powerOnAtStartUp = TRUE
EOF
print VMX <<EOF if $serial;
serial0.present = TRUE
serial0.fileType = "pipe"
serial0.fileName = "pintos.socket"
serial0.pipe.endPoint = "client"
serial0.tryNoRxLoss = "TRUE"
EOF
for (my ($i) = 0; $i < 4; $i++) {
my ($dsk) = $disks[$i];
last if !defined $dsk;
my ($device) = "ide" . int ($i / 2) . ":" . ($i % 2);
my ($pln) = "$device.pln";
print VMX <<EOF;
$device.present = TRUE
$device.deviceType = "plainDisk"
$device.fileName = "$pln"
EOF
open (URANDOM, '<', '/dev/urandom') or die "/dev/urandom: open: $!\n";
my ($bytes);
sysread (URANDOM, $bytes, 4) == 4 or die "/dev/urandom: read: $!\n";
close (URANDOM);
my ($cid) = unpack ("L", $bytes);
my (%geom) = disk_geometry ($dsk);
open (PLN, ">", $pln) or die "$pln: create: $!\n";
print PLN <<EOF;
version=1
CID=$cid
parentCID=ffffffff
createType="monolithicFlat"
RW $geom{CAPACITY} FLAT "$dsk" 0
# The Disk Data Base
#DDB
ddb.adapterType = "ide"
ddb.virtualHWVersion = "4"
ddb.toolsVersion = "2"
ddb.geometry.cylinders = "$geom{C}"
ddb.geometry.heads = "$geom{H}"
ddb.geometry.sectors = "$geom{S}"
EOF
close (PLN);
}
close (VMX);
my ($squish_unix);
if ($serial) {
$squish_unix = find_in_path ("squish-unix");
print "warning: can't find squish-unix, so terminal input ",
"and output will fail\n" if !defined $squish_unix;
}
my ($vmx) = getcwd () . "/pintos.vmx";
my (@cmd) = ("vmplayer", $vmx);
unshift (@cmd, $squish_unix, "pintos.socket") if $squish_unix;
print join (' ', @cmd), "\n";
xsystem (@cmd);
}
# Disk utilities.
sub extend_file {
my ($handle, $file_name, $size) = @_;
if (-s ($handle) < $size) {
sysseek ($handle, $size - 1, 0) == $size - 1
or die "$file_name: seek: $!\n";
syswrite ($handle, "\0") == 1
or die "$file_name: write: $!\n";
}
}
# disk_geometry($file)
#
# Examines $file and returns a valid IDE disk geometry for it, as a
# hash.
sub disk_geometry {
my ($file) = @_;
my ($size) = -s $file;
die "$file: stat: $!\n" if !defined $size;
die "$file: size $size not a multiple of 512 bytes\n" if $size % 512;
my ($cyl_size) = 512 * 16 * 63;
my ($cylinders) = ceil ($size / $cyl_size);
return (CAPACITY => $size / 512,
C => $cylinders,
H => 16,
S => 63);
}
# Subprocess utilities.
# run_command(@args)
#
# Runs xsystem(@args).
# Also prints the command it's running and checks that it succeeded.
sub run_command {
print join (' ', @_), "\n";
die "command failed\n" if xsystem (@_);
}
# xsystem(@args)
#
# Creates a subprocess via exec(@args) and waits for it to complete.
# Relays common signals to the subprocess.
# If $timeout is set then the subprocess will be killed after that long.
sub xsystem {
# QEMU turns off local echo and does not restore it if killed by a signal.
# We compensate by restoring it ourselves.
my $cleanup = sub {};
if (isatty (0)) {
my $termios = POSIX::Termios->new;
$termios->getattr (0);
$cleanup = sub { $termios->setattr (0, &POSIX::TCSANOW); }
}
# Create pipe for filtering output.
pipe (my $in, my $out) or die "pipe: $!\n" if $kill_on_failure;
my ($pid) = fork;
if (!defined ($pid)) {
# Fork failed.
die "fork: $!\n";
} elsif (!$pid) {
# Running in child process.
dup2 (fileno ($out), STDOUT_FILENO) or die "dup2: $!\n"
if $kill_on_failure;
exec_setitimer (@_);
} else {
# Running in parent process.
close $out if $kill_on_failure;
my ($cause);
local $SIG{ALRM} = sub { timeout ($pid, $cause, $cleanup); };
local $SIG{INT} = sub { relay_signal ($pid, "INT", $cleanup); };
local $SIG{TERM} = sub { relay_signal ($pid, "TERM", $cleanup); };
alarm ($timeout * get_load_average () + 1) if defined ($timeout);
if ($kill_on_failure) {
# Filter output.
my ($buf) = "";
my ($boots) = 0;
local ($|) = 1;
for (;;) {
if (waitpid ($pid, WNOHANG) != 0) {
# Subprocess died. Pass through any remaining data.
do { print $buf } while sysread ($in, $buf, 4096) > 0;
last;
}
# Read and print out pipe data.
my ($len) = length ($buf);
waitpid ($pid, 0), last
if sysread ($in, $buf, 4096, $len) <= 0;
print substr ($buf, $len);
# Remove full lines from $buf and scan them for keywords.
while ((my $idx = index ($buf, "\n")) >= 0) {
local $_ = substr ($buf, 0, $idx + 1, '');
next if defined ($cause);
if (/(Kernel PANIC|User process ABORT)/ ) {
$cause = "\L$1\E";
alarm (5);
} elsif (/PintOS booting/ && ++$boots > 1) {
$cause = "triple fault";
alarm (5);
} elsif (/FAILED/) {
$cause = "test failure";
alarm (5);
}
}
}
} else {
waitpid ($pid, 0);
}
alarm (0);
&$cleanup ();
if (WIFSIGNALED ($?) && WTERMSIG ($?) == SIGVTALRM2 ()) {
seek (STDOUT, 0, 2);
print "\nTIMEOUT after $timeout seconds of host CPU time\n";
exit 0;
}
return $?;
}
}
# relay_signal($pid, $signal, &$cleanup)
#
# Relays $signal to $pid and then reinvokes it for us with the default
# handler. Also cleans up temporary files and invokes $cleanup.
sub relay_signal {
my ($pid, $signal, $cleanup) = @_;
kill $signal, $pid;
eval { File::Temp::cleanup() }; # Not defined in old File::Temp.
&$cleanup ();
$SIG{$signal} = 'DEFAULT';
kill $signal, getpid ();
}
# timeout($pid, $cause, &$cleanup)
#
# Interrupts $pid and dies with a timeout error message,
# after invoking $cleanup.
sub timeout {
my ($pid, $cause, $cleanup) = @_;
kill "INT", $pid;
waitpid ($pid, 0);
&$cleanup ();
seek (STDOUT, 0, 2);
if (!defined ($cause)) {
my ($load_avg) = `uptime` =~ /(load average:.*)$/i;
print "\nTIMEOUT after ", time () - $start_time,
" seconds of wall-clock time";
print " - $load_avg" if defined $load_avg;
print "\n";
} else {
print "Simulation terminated due to $cause.\n";
}
exit 0;
}
# Returns the system load average over the last minute.
# If the load average is less than 1.0 or cannot be determined, returns 1.0.
sub get_load_average {
my $avg;
if ($^O eq 'darwin') {
$avg = (split /\s/, `uptime`)[11];
} else {
$avg = `uptime` =~ /load average:\s*([^,]+),/;
}
return $avg >= 1.0 ? $avg : 1.0;
}
# Calls setitimer to set a timeout, then execs what was passed to us.
sub exec_setitimer {
if (defined $timeout) {
if ($] ge 5.8.0 && $^O ne 'darwin') {
eval "
use Time::HiRes qw(setitimer ITIMER_VIRTUAL);
setitimer (ITIMER_VIRTUAL, $timeout, 0);
";
} else {
{ exec ("setitimer-helper", $timeout, @_); };
exit 1 if !$!{ENOENT};
print STDERR "warning: setitimer-helper is not installed, so ",
"CPU time limit will not be enforced\n";
}
}
exec (@_);
exit (1);
}
sub SIGVTALRM2 {
use Config;
my $i = 0;
foreach my $name (split(' ', $Config{sig_name})) {
return $i if $name eq 'VTALRM';
$i++;
}
return 0;
}
# find_in_path ($program)
#
# Searches for $program in $ENV{PATH}.
# Returns $program if found, otherwise undef.
sub find_in_path {
my ($program) = @_;
-x "$_/$program" and return $program foreach split (':', $ENV{PATH});
return;
}

28
src/utils/pintos-gdb Executable file
View File

@@ -0,0 +1,28 @@
#! /bin/sh
# Expects to be called from with a given task's build directory
# Relative path to GDB macros file within PintOS repo.
# Customize for your machine if required.
GDBMACROS=../../misc/gdb-macros
# Choose correct GDB for the current environment:
GDB=gdb
UNAME_S=`uname -s`
if test "$UNAME_S" = "Darwin"; then
GDB=i686-elf-gdb
fi
if command -v i386-elf-gdb >/dev/null 2>&1; then
GDB=i386-elf-gdb
fi
# Run GDB.
if test -f "$GDBMACROS"; then
exec $GDB -x "$GDBMACROS" "$@"
else
echo "*** $GDBMACROS does not exist ***"
echo "*** PintOS GDB macros will not be available ***"
exec $GDB "$@"
fi

134
src/utils/pintos-mkdisk Executable file
View File

@@ -0,0 +1,134 @@
#! /usr/bin/perl
use strict;
use warnings;
use POSIX;
use Getopt::Long qw(:config bundling);
use Fcntl 'SEEK_SET';
# Read Pintos.pm from the same directory as this program.
BEGIN { my $self = $0; $self =~ s%/+[^/]*$%%; require "$self/Pintos.pm"; }
our ($disk_fn); # Output disk file name.
our (%parts); # Partitions.
our ($format); # "partitioned" (default) or "raw"
our (%geometry); # IDE disk geometry.
our ($align); # Align partitions on cylinders?
our ($loader_fn); # File name of loader.
our ($include_loader); # Include loader?
our (@kernel_args); # Kernel arguments.
if (grep ($_ eq '--', @ARGV)) {
@kernel_args = @ARGV;
@ARGV = ();
while ((my $arg = shift (@kernel_args)) ne '--') {
push (@ARGV, $arg);
}
}
GetOptions ("h|help" => sub { usage (0); },
"kernel=s" => \&set_part,
"filesys=s" => \&set_part,
"scratch=s" => \&set_part,
"swap=s" => \&set_part,
"filesys-size=s" => \&set_part,
"scratch-size=s" => \&set_part,
"swap-size=s" => \&set_part,
"kernel-from=s" => \&set_part,
"filesys-from=s" => \&set_part,
"scratch-from=s" => \&set_part,
"swap-from=s" => \&set_part,
"format=s" => \$format,
"loader:s" => \&set_loader,
"no-loader" => \&set_no_loader,
"geometry=s" => \&set_geometry,
"align=s" => \&set_align)
or exit 1;
usage (1) if @ARGV != 1;
$disk_fn = $ARGV[0];
die "$disk_fn: already exists\n" if -e $disk_fn;
# Sets the loader to copy to the MBR.
sub set_loader {
die "can't specify both --loader and --no-loader\n"
if defined ($include_loader) && !$include_loader;
$include_loader = 1;
$loader_fn = $_[1] if $_[1] ne '';
}
# Disables copying a loader to the MBR.
sub set_no_loader {
die "can't specify both --loader and --no-loader\n"
if defined ($include_loader) && $include_loader;
$include_loader = 0;
}
# Figure out whether to include a loader.
$include_loader = exists ($parts{KERNEL}) && $format eq 'partitioned'
if !defined ($include_loader);
die "can't write loader to raw disk\n" if $include_loader && $format eq 'raw';
die "can't write command-line arguments without --loader or --kernel\n"
if @kernel_args && !$include_loader;
print STDERR "warning: --loader only makes sense without --kernel "
. "if this disk will be used to load a kernel from another disk\n"
if $include_loader && !exists ($parts{KERNEL});
# Open disk.
my ($disk_handle);
open ($disk_handle, '>', $disk_fn) or die "$disk_fn: create: $!\n";
# Read loader.
my ($loader);
$loader = read_loader ($loader_fn) if $include_loader;
# Write disk.
my (%disk) = %parts;
$disk{DISK} = $disk_fn;
$disk{HANDLE} = $disk_handle;
$disk{ALIGN} = $align;
$disk{GEOMETRY} = %geometry;
$disk{FORMAT} = $format;
$disk{LOADER} = $loader;
$disk{ARGS} = \@kernel_args;
assemble_disk (%disk);
# Done.
exit 0;
sub usage {
print <<'EOF';
pintos-mkdisk, a utility for creating PintOS virtual disks
Usage: pintos-mkdisk [OPTIONS] DISK [-- ARGUMENT...]
where DISK is the virtual disk to create,
each ARGUMENT is inserted into the command line written to DISK,
and each OPTION is one of the following options.
Partition options: (where PARTITION is one of: kernel filesys scratch swap)
--PARTITION=FILE Use a copy of FILE for the given PARTITION
--PARTITION-size=SIZE Create an empty PARTITION of the given SIZE in MB
--PARTITION-from=DISK Use of a copy of the given PARTITION in DISK
(There is no --kernel-size option.)
Output disk options:
--format=partitioned Write partition table to output (default)
--format=raw Do not write partition table to output
(PintOS can only use partitioned disks.)
Partitioned format output options:
--loader[=FILE] Get bootstrap loader from FILE (default: loader.bin
if --kernel option is specified, empty otherwise)
--no-loader Do not include a bootstrap loader
--geometry=H,S Use H head, S sector geometry (default: 16, 63)
--geometry=zip Use 64 head, 32 sector geometry for USB-ZIP boot
per http://syslinux.zytor.com/usbkey.php
--align=bochs Round size to cylinder for Bochs support (default)
--align=full Align partition boundaries to cylinder boundary to
let fdisk guess correct geometry and quiet warnings
--align=none Don't align partitions at all, to save space
Other options:
-h, --help Display this help message.
EOF
exit ($_[0]);
}

View File

@@ -0,0 +1,42 @@
#! /usr/bin/perl -w
use strict;
use Fcntl 'SEEK_SET';
# Read Pintos.pm from the same directory as this program.
BEGIN { my $self = $0; $self =~ s%/+[^/]*$%%; require "$self/Pintos.pm"; }
# Get command-line arguments.
usage (0) if @ARGV == 1 && $ARGV[0] eq '--help';
usage (1) if @ARGV < 2 || $ARGV[1] ne '--';
my ($disk, undef, @kernel_args) = @ARGV;
# Open disk.
my ($handle);
open ($handle, '+<', $disk) or die "$disk: open: $!\n";
# Check that it's a partitioned disk with a PintOS loader.
my ($buffer) = read_fully ($handle, $disk, 512);
unpack ("x510 v", $buffer) == 0xaa55 or die "$disk: not a partitioned disk\n";
$buffer =~ /PintOS/ or die "$disk: does not contain PintOS loader\n";
# Write the command line.
our ($LOADER_SIZE);
sysseek ($handle, $LOADER_SIZE, SEEK_SET) == $LOADER_SIZE
or die "$disk: seek: $!\n";
write_fully ($handle, $disk, make_kernel_command_line (@kernel_args));
# Close disk.
close ($handle) or die "$disk: close: $!\n";
exit 0;
sub usage {
print <<'EOF';
pintos-set-cmdline, a utility for changing the command line in PintOS disks
Usage: pintos-set-cmdline DISK -- [ARGUMENT...]
where DISK is a bootable disk containing a PintOS loader
and each ARGUMENT is inserted into the command line written to DISK.
EOF
exit ($_[0]);
}

View File

@@ -0,0 +1,49 @@
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
int
main (int argc, char *argv[])
{
const char *program_name = argv[0];
double timeout;
if (argc < 3)
{
fprintf (stderr,
"setitimer-helper: runs a program with a virtual CPU limit\n"
"usage: %s TIMEOUT PROGRAM [ARG...]\n"
" where TIMEOUT is the virtual CPU limit, in seconds,\n"
" and remaining arguments specify the program to run\n"
" and its argument.\n",
program_name);
return EXIT_FAILURE;
}
timeout = strtod (argv[1], NULL);
if (timeout >= 0.0 && timeout < LONG_MAX)
{
struct itimerval it;
it.it_interval.tv_sec = 0;
it.it_interval.tv_usec = 0;
it.it_value.tv_sec = timeout;
it.it_value.tv_usec = (timeout - floor (timeout)) * 1000000;
if (setitimer (ITIMER_VIRTUAL, &it, NULL) < 0)
fprintf (stderr, "%s: setitimer: %s\n",
program_name, strerror (errno));
}
else
fprintf (stderr, "%s: invalid timeout value \"%s\"\n",
program_name, argv[1]);
execvp (argv[2], &argv[2]);
fprintf (stderr, "%s: couldn't exec \"%s\": %s\n",
program_name, argv[2], strerror (errno));
return EXIT_FAILURE;
}

345
src/utils/squish-pty.c Normal file
View File

@@ -0,0 +1,345 @@
#define _GNU_SOURCE 1
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
static void
fail_io (const char *msg, ...)
__attribute__ ((noreturn))
__attribute__ ((format (printf, 1, 2)));
/* Prints MSG, formatting as with printf(),
plus an error message based on errno,
and exits. */
static void
fail_io (const char *msg, ...)
{
va_list args;
va_start (args, msg);
vfprintf (stderr, msg, args);
va_end (args);
if (errno != 0)
fprintf (stderr, ": %s", strerror (errno));
putc ('\n', stderr);
exit (EXIT_FAILURE);
}
/* If FD is a terminal, configures it for noncanonical input mode
with VMIN and VTIME set as indicated.
If FD is not a terminal, has no effect. */
static void
make_noncanon (int fd, int vmin, int vtime)
{
if (isatty (fd))
{
struct termios termios;
if (tcgetattr (fd, &termios) < 0)
fail_io ("tcgetattr");
termios.c_lflag &= ~(ICANON | ECHO);
termios.c_cc[VMIN] = vmin;
termios.c_cc[VTIME] = vtime;
if (tcsetattr (fd, TCSANOW, &termios) < 0)
fail_io ("tcsetattr");
}
}
/* Make FD non-blocking if NONBLOCKING is true,
or blocking if NONBLOCKING is false. */
static void
make_nonblocking (int fd, bool nonblocking)
{
int flags = fcntl (fd, F_GETFL);
if (flags < 0)
fail_io ("fcntl");
if (nonblocking)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
if (fcntl (fd, F_SETFL, flags) < 0)
fail_io ("fcntl");
}
/* Handle a read or write on *FD, which is the pty if FD_IS_PTY
is true, that returned end-of-file or error indication RETVAL.
The system call is named CALL, for use in error messages.
Returns true if processing may continue, false if we're all
done. */
static bool
handle_error (ssize_t retval, int *fd, bool fd_is_pty, const char *call)
{
if (fd_is_pty)
{
if (retval < 0)
{
if (errno == EIO)
{
/* Slave side of pty has been closed. */
return false;
}
else
fail_io ("%s", call);
}
else
return true;
}
else
{
if (retval == 0)
{
close (*fd);
*fd = -1;
return true;
}
else
fail_io ("%s", call);
}
}
/* Copies data from stdin to PTY and from PTY to stdout until no
more data can be read or written. */
static void
relay (int pty, int dead_child_fd)
{
struct pipe
{
int in, out;
char buf[BUFSIZ];
size_t size, ofs;
bool active;
};
struct pipe pipes[2];
/* Make PTY, stdin, and stdout non-blocking. */
make_nonblocking (pty, true);
make_nonblocking (STDIN_FILENO, true);
make_nonblocking (STDOUT_FILENO, true);
/* Configure noncanonical mode on PTY and stdin to avoid
waiting for end-of-line. We want to minimize context
switching on PTY (for efficiency) and minimize latency on
stdin to avoid a laggy user experience. */
make_noncanon (pty, 16, 1);
make_noncanon (STDIN_FILENO, 1, 0);
memset (pipes, 0, sizeof pipes);
pipes[0].in = STDIN_FILENO;
pipes[0].out = pty;
pipes[1].in = pty;
pipes[1].out = STDOUT_FILENO;
while (pipes[0].in != -1 || pipes[1].in != -1)
{
fd_set read_fds, write_fds;
int retval;
int i;
FD_ZERO (&read_fds);
FD_ZERO (&write_fds);
for (i = 0; i < 2; i++)
{
struct pipe *p = &pipes[i];
/* Don't do anything with the stdin->pty pipe until we
have some data for the pty->stdout pipe. If we get
too eager, Bochs will throw away our input. */
if (i == 0 && !pipes[1].active)
continue;
if (p->in != -1 && p->size + p->ofs < sizeof p->buf)
FD_SET (p->in, &read_fds);
if (p->out != -1 && p->size > 0)
FD_SET (p->out, &write_fds);
}
FD_SET (dead_child_fd, &read_fds);
do
{
retval = select (FD_SETSIZE, &read_fds, &write_fds, NULL, NULL);
}
while (retval < 0 && errno == EINTR);
if (retval < 0)
fail_io ("select");
if (FD_ISSET (dead_child_fd, &read_fds))
{
/* Child died. Do final relaying. */
struct pipe *p = &pipes[1];
if (p->out == -1)
return;
make_nonblocking (STDOUT_FILENO, false);
for (;;)
{
ssize_t n;
/* Write buffer. */
while (p->size > 0)
{
n = write (p->out, p->buf + p->ofs, p->size);
if (n < 0)
fail_io ("write");
else if (n == 0)
fail_io ("zero-length write");
p->ofs += n;
p->size -= n;
}
p->ofs = 0;
p->size = n = read (p->in, p->buf, sizeof p->buf);
if (n <= 0)
return;
}
}
for (i = 0; i < 2; i++)
{
struct pipe *p = &pipes[i];
if (p->in != -1 && FD_ISSET (p->in, &read_fds))
{
ssize_t n = read (p->in, p->buf + p->ofs + p->size,
sizeof p->buf - p->ofs - p->size);
if (n > 0)
{
p->active = true;
p->size += n;
if (p->size == BUFSIZ && p->ofs != 0)
{
memmove (p->buf, p->buf + p->ofs, p->size);
p->ofs = 0;
}
}
else if (!handle_error (n, &p->in, p->in == pty, "read"))
return;
}
if (p->out != -1 && FD_ISSET (p->out, &write_fds))
{
ssize_t n = write (p->out, p->buf + p->ofs, p->size);
if (n > 0)
{
p->ofs += n;
p->size -= n;
if (p->size == 0)
p->ofs = 0;
}
else if (!handle_error (n, &p->out, p->out == pty, "write"))
return;
}
}
}
}
static int dead_child_fd;
static void
sigchld_handler (int signo __attribute__ ((unused)))
{
if (write (dead_child_fd, "", 1) < 0)
_exit (1);
}
int
main (int argc __attribute__ ((unused)), char *argv[])
{
int master, slave;
char *name;
pid_t pid;
struct sigaction sa;
int pipe_fds[2];
struct itimerval zero_itimerval, old_itimerval;
if (argc < 2)
{
fprintf (stderr,
"usage: squish-pty COMMAND [ARG]...\n"
"Squishes both stdin and stdout into a single pseudoterminal,\n"
"which is passed as stdout to run the specified COMMAND.\n");
return EXIT_FAILURE;
}
/* Open master side of pty and get ready to open slave. */
master = open ("/dev/ptmx", O_RDWR | O_NOCTTY);
if (master < 0)
fail_io ("open \"/dev/ptmx\"");
if (grantpt (master) < 0)
fail_io ("grantpt");
if (unlockpt (master) < 0)
fail_io ("unlockpt");
/* Open slave side of pty. */
name = ptsname (master);
if (name == NULL)
fail_io ("ptsname");
slave = open (name, O_RDWR);
if (slave < 0)
fail_io ("open \"%s\"", name);
/* Arrange to get notified when a child dies, by writing a byte
to a pipe fd. We really want to use pselect() and
sigprocmask(), but Solaris 2.7 doesn't have it. */
if (pipe (pipe_fds) < 0)
fail_io ("pipe");
dead_child_fd = pipe_fds[1];
memset (&sa, 0, sizeof sa);
sa.sa_handler = sigchld_handler;
sigemptyset (&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction (SIGCHLD, &sa, NULL) < 0)
fail_io ("sigaction");
/* Save the virtual interval timer, which might have been set
by the process that ran us. It really should be applied to
our child process. */
memset (&zero_itimerval, 0, sizeof zero_itimerval);
if (setitimer (ITIMER_VIRTUAL, &zero_itimerval, &old_itimerval) < 0)
fail_io ("setitimer");
pid = fork ();
if (pid < 0)
fail_io ("fork");
else if (pid != 0)
{
/* Running in parent process. */
int status;
close (slave);
relay (master, pipe_fds[0]);
/* If the subprocess has died, die in the same fashion.
In particular, dying from SIGVTALRM tells the pintos
script that we ran out of CPU time. */
if (waitpid (pid, &status, WNOHANG) > 0)
{
if (WIFEXITED (status))
return WEXITSTATUS (status);
else if (WIFSIGNALED (status))
raise (WTERMSIG (status));
}
return 0;
}
else
{
/* Running in child process. */
if (setitimer (ITIMER_VIRTUAL, &old_itimerval, NULL) < 0)
fail_io ("setitimer");
if (dup2 (slave, STDOUT_FILENO) < 0)
fail_io ("dup2");
if (close (pipe_fds[0]) < 0 || close (pipe_fds[1]) < 0
|| close (slave) < 0 || close (master) < 0)
fail_io ("close");
execvp (argv[1], argv + 1);
fail_io ("exec");
}
}

337
src/utils/squish-unix.c Normal file
View File

@@ -0,0 +1,337 @@
#define _GNU_SOURCE 1
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <termios.h>
#include <unistd.h>
static void
fail_io (const char *msg, ...)
__attribute__ ((noreturn))
__attribute__ ((format (printf, 1, 2)));
/* Prints MSG, formatting as with printf(),
plus an error message based on errno,
and exits. */
static void
fail_io (const char *msg, ...)
{
va_list args;
va_start (args, msg);
vfprintf (stderr, msg, args);
va_end (args);
if (errno != 0)
fprintf (stderr, ": %s", strerror (errno));
putc ('\n', stderr);
exit (EXIT_FAILURE);
}
/* If FD is a terminal, configures it for noncanonical input mode
with VMIN and VTIME set as indicated.
If FD is not a terminal, has no effect. */
static void
make_noncanon (int fd, int vmin, int vtime)
{
if (isatty (fd))
{
struct termios termios;
if (tcgetattr (fd, &termios) < 0)
fail_io ("tcgetattr");
termios.c_lflag &= ~(ICANON | ECHO);
termios.c_cc[VMIN] = vmin;
termios.c_cc[VTIME] = vtime;
if (tcsetattr (fd, TCSANOW, &termios) < 0)
fail_io ("tcsetattr");
}
}
/* Make FD non-blocking if NONBLOCKING is true,
or blocking if NONBLOCKING is false. */
static void
make_nonblocking (int fd, bool nonblocking)
{
int flags = fcntl (fd, F_GETFL);
if (flags < 0)
fail_io ("fcntl");
if (nonblocking)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
if (fcntl (fd, F_SETFL, flags) < 0)
fail_io ("fcntl");
}
/* Handle a read or write on *FD, which is the socket if
FD_IS_SOCK is true, that returned end-of-file or error
indication RETVAL. The system call is named CALL, for use in
error messages. Returns true if processing may continue,
false if we're all done. */
static bool
handle_error (ssize_t retval, int *fd, bool fd_is_sock, const char *call)
{
if (retval == 0)
{
if (fd_is_sock)
return false;
else
{
*fd = -1;
return true;
}
}
else
fail_io ("%s", call);
}
/* Copies data from stdin to SOCK and from SOCK to stdout until no
more data can be read or written. */
static void
relay (int sock)
{
struct pipe
{
int in, out;
char buf[BUFSIZ];
size_t size, ofs;
bool active;
};
struct pipe pipes[2];
/* In case stdin is a file, go back to the beginning.
This allows replaying the input on reset. */
lseek (STDIN_FILENO, 0, SEEK_SET);
/* Make SOCK, stdin, and stdout non-blocking. */
make_nonblocking (sock, true);
make_nonblocking (STDIN_FILENO, true);
make_nonblocking (STDOUT_FILENO, true);
/* Configure noncanonical mode on stdin to avoid waiting for
end-of-line. */
make_noncanon (STDIN_FILENO, 1, 0);
memset (pipes, 0, sizeof pipes);
pipes[0].in = STDIN_FILENO;
pipes[0].out = sock;
pipes[1].in = sock;
pipes[1].out = STDOUT_FILENO;
while (pipes[0].in != -1 || pipes[1].in != -1
|| (pipes[1].size && pipes[1].out != -1))
{
fd_set read_fds, write_fds;
sigset_t empty_set;
int retval;
int i;
FD_ZERO (&read_fds);
FD_ZERO (&write_fds);
for (i = 0; i < 2; i++)
{
struct pipe *p = &pipes[i];
/* Don't do anything with the stdin->sock pipe until we
have some data for the sock->stdout pipe. If we get
too eager, vmplayer will throw away our input. */
if (i == 0 && !pipes[1].active)
continue;
if (p->in != -1 && p->size + p->ofs < sizeof p->buf)
FD_SET (p->in, &read_fds);
if (p->out != -1 && p->size > 0)
FD_SET (p->out, &write_fds);
}
sigemptyset (&empty_set);
retval = pselect (FD_SETSIZE, &read_fds, &write_fds, NULL, NULL,
&empty_set);
if (retval < 0)
{
if (errno == EINTR)
{
/* Child died. Do final relaying. */
struct pipe *p = &pipes[1];
if (p->out == -1)
exit (0);
make_nonblocking (STDOUT_FILENO, false);
for (;;)
{
ssize_t n;
/* Write buffer. */
while (p->size > 0)
{
n = write (p->out, p->buf + p->ofs, p->size);
if (n < 0)
fail_io ("write");
else if (n == 0)
fail_io ("zero-length write");
p->ofs += n;
p->size -= n;
}
p->ofs = 0;
p->size = n = read (p->in, p->buf, sizeof p->buf);
if (n <= 0)
exit (0);
}
}
fail_io ("select");
}
for (i = 0; i < 2; i++)
{
struct pipe *p = &pipes[i];
if (p->in != -1 && FD_ISSET (p->in, &read_fds))
{
ssize_t n = read (p->in, p->buf + p->ofs + p->size,
sizeof p->buf - p->ofs - p->size);
if (n > 0)
{
p->active = true;
p->size += n;
if (p->size == BUFSIZ && p->ofs != 0)
{
memmove (p->buf, p->buf + p->ofs, p->size);
p->ofs = 0;
}
}
else if (!handle_error (n, &p->in, p->in == sock, "read"))
return;
}
if (p->out != -1 && FD_ISSET (p->out, &write_fds))
{
ssize_t n = write (p->out, p->buf + p->ofs, p->size);
if (n > 0)
{
p->ofs += n;
p->size -= n;
if (p->size == 0)
p->ofs = 0;
}
else if (!handle_error (n, &p->out, p->out == sock, "write"))
return;
}
}
}
}
static void
sigchld_handler (int signo __attribute__ ((unused)))
{
/* Nothing to do. */
}
int
main (int argc __attribute__ ((unused)), char *argv[])
{
pid_t pid;
struct itimerval zero_itimerval;
struct sockaddr_un sun;
sigset_t sigchld_set;
int sock;
if (argc < 3)
{
fprintf (stderr,
"usage: squish-unix SOCKET COMMAND [ARG]...\n"
"Squishes both stdin and stdout into a single Unix domain\n"
"socket named SOCKET, and runs COMMAND as a subprocess.\n");
return EXIT_FAILURE;
}
/* Create socket. */
sock = socket (PF_LOCAL, SOCK_STREAM, 0);
if (sock < 0)
fail_io ("socket");
/* Configure socket. */
sun.sun_family = AF_LOCAL;
strncpy (sun.sun_path, argv[1], sizeof sun.sun_path);
sun.sun_path[sizeof sun.sun_path - 1] = '\0';
if (unlink (sun.sun_path) < 0 && errno != ENOENT)
fail_io ("unlink");
if (bind (sock, (struct sockaddr *) &sun,
(offsetof (struct sockaddr_un, sun_path)
+ strlen (sun.sun_path) + 1)) < 0)
fail_io ("bind");
/* Listen on socket. */
if (listen (sock, 1) < 0)
fail_io ("listen");
/* Block SIGCHLD and set up a handler for it. */
sigemptyset (&sigchld_set);
sigaddset (&sigchld_set, SIGCHLD);
if (sigprocmask (SIG_BLOCK, &sigchld_set, NULL) < 0)
fail_io ("sigprocmask");
if (signal (SIGCHLD, sigchld_handler) == SIG_ERR)
fail_io ("signal");
/* Save the virtual interval timer, which might have been set
by the process that ran us. It really should be applied to
our child process. */
memset (&zero_itimerval, 0, sizeof zero_itimerval);
if (setitimer (ITIMER_VIRTUAL, &zero_itimerval, NULL) < 0)
fail_io ("setitimer");
pid = fork ();
if (pid < 0)
fail_io ("fork");
else if (pid != 0)
{
/* Running in parent process. */
make_nonblocking (sock, true);
for (;;)
{
fd_set read_fds;
sigset_t empty_set;
int retval;
int conn;
/* Wait for connection. */
FD_ZERO (&read_fds);
FD_SET (sock, &read_fds);
sigemptyset (&empty_set);
retval = pselect (sock + 1, &read_fds, NULL, NULL, NULL, &empty_set);
if (retval < 0)
{
if (errno == EINTR)
break;
fail_io ("select");
}
/* Accept connection. */
conn = accept (sock, NULL, NULL);
if (conn < 0)
fail_io ("accept");
/* Relay connection. */
relay (conn);
close (conn);
}
return 0;
}
else
{
/* Running in child process. */
if (close (sock) < 0)
fail_io ("close");
execvp (argv[2], argv + 2);
fail_io ("exec");
}
}