diff options
Diffstat (limited to 'src/utils')
| -rw-r--r-- | src/utils/.cvsignore | 3 | ||||
| -rw-r--r-- | src/utils/Makefile | 12 | ||||
| -rw-r--r-- | src/utils/backtrace | 106 | ||||
| -rwxr-xr-x | src/utils/pintos | 888 | ||||
| -rw-r--r-- | src/utils/pintos-gdb | 20 | ||||
| -rw-r--r-- | src/utils/pintos-mkdisk | 37 | ||||
| -rw-r--r-- | src/utils/setitimer-helper.c | 49 | ||||
| -rw-r--r-- | src/utils/squish-pty.c | 355 | ||||
| -rw-r--r-- | src/utils/squish-unix.c | 354 |
9 files changed, 1824 insertions, 0 deletions
diff --git a/src/utils/.cvsignore b/src/utils/.cvsignore new file mode 100644 index 0000000..b96f278 --- /dev/null +++ b/src/utils/.cvsignore @@ -0,0 +1,3 @@ +setitimer-helper +squish-pty +squish-unix diff --git a/src/utils/Makefile b/src/utils/Makefile new file mode 100644 index 0000000..3e72ef4 --- /dev/null +++ b/src/utils/Makefile @@ -0,0 +1,12 @@ +all: setitimer-helper squish-pty squish-unix + +CC = gcc +CFLAGS = -Wall -W -D_XOPEN_SOURCE=500 -D__EXTENSIONS__ +#LDFLAGS = -lm -lxnet +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 diff --git a/src/utils/backtrace b/src/utils/backtrace new file mode 100644 index 0000000..95e422f --- /dev/null +++ b/src/utils/backtrace @@ -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 ("i386-elf-addr2line") || search_path ("addr2line"); +if (!$a2l) { + die "backtrace: neither `i386-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"; +} diff --git a/src/utils/pintos b/src/utils/pintos new file mode 100755 index 0000000..dacf900 --- /dev/null +++ b/src/utils/pintos @@ -0,0 +1,888 @@ +#! /usr/bin/perl -w + +use strict; +use POSIX; +use Fcntl; +use File::Temp 'tempfile'; +use Getopt::Long qw(:config bundling); + +# 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 (%disks) = (OS => {DEF_FN => 'os.dsk'}, # Disks to give VM. + FS => {DEF_FN => 'fs.dsk'}, + SCRATCH => {DEF_FN => 'scratch.dsk'}, + SWAP => {DEF_FN => 'swap.dsk'}); +our (@disks_by_iface) = @disks{qw (OS FS SCRATCH SWAP)}; + +parse_command_line (); +find_disks (); +prepare_scratch_disk (); +prepare_arguments (); +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 (@_) }, + "bochs" => sub { set_sim ("bochs") }, + "qemu" => sub { set_sim ("qemu") }, + "player" => sub { set_sim ("player") }, + + "debug=s" => sub { set_debug (@_) }, + "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); }, + + "os-disk=s" => \$disks{OS}{FILE_NAME}, + "fs-disk=s" => \$disks{FS}{FILE_NAME}, + "scratch-disk=s" => \$disks{SCRATCH}{FILE_NAME}, + "swap-disk=s" => \$disks{SWAP}{FILE_NAME}, + + "0|disk-0|hda=s" => \$disks_by_iface[0]{FILE_NAME}, + "1|disk-1|hdb=s" => \$disks_by_iface[1]{FILE_NAME}, + "2|disk-2|hdc=s" => \$disks_by_iface[2]{FILE_NAME}, + "3|disk-3|hdd=s" => \$disks_by_iface[3]{FILE_NAME}) + or exit 1; + } + + $sim = "bochs" if !defined $sim; + $debug = "none" if !defined $debug; + $vga = "window" 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; +} + +# 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: + --bochs (default) Use Bochs as simulator + --qemu Use QEMU 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 (for `run' command): + -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 +Disk options: (name an existing FILE or specify SIZE in MB for a temp disk) + --os-disk=FILE Set OS disk file (default: os.dsk) + --fs-disk=FILE|SIZE Set FS disk file (default: fs.dsk) + --scratch-disk=FILE|SIZE Set scratch disk (default: scratch.dsk) + --swap-disk=FILE|SIZE Set swap disk file (default: swap.dsk) +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; +} + +# Locates the files used to back each of the virtual disks, +# and creates temporary disks. +sub find_disks { + for my $disk (values %disks) { + # If there's no assigned file name but the default file exists, + # try to assign a default file name. + if (!defined ($disk->{FILE_NAME})) { + for my $try_fn ($disk->{DEF_FN}, "build/" . $disk->{DEF_FN}) { + $disk->{FILE_NAME} = $try_fn, last + if -e $try_fn; + } + } + + # If there's no file name, we're done. + next if !defined ($disk->{FILE_NAME}); + + if ($disk->{FILE_NAME} =~ /^\d+(\.\d+)?|\.\d+$/) { + # Create a temporary disk of approximately the specified + # size in megabytes. + die "OS disk can't be temporary\n" if $disk == $disks{OS}; + + my ($mb) = $disk->{FILE_NAME}; + undef $disk->{FILE_NAME}; + + my ($cyl_size) = 512 * 16 * 63; + extend_disk ($disk, ceil ($mb * 2) * $cyl_size); + } else { + # The file must exist and have nonzero size. + -e $disk->{FILE_NAME} or die "$disk->{FILE_NAME}: stat: $!\n"; + -s _ or die "$disk->{FILE_NAME}: disk has zero size\n"; + } + } + + # Warn about (potentially) missing disks. + die "Cannot find OS disk\n" if !defined $disks{OS}{FILE_NAME}; + if (my ($project) = `pwd` =~ /\b(threads|userprog|vm|filesys)\b/) { + if ((grep ($project eq $_, qw (userprog vm filesys))) + && !defined ($disks{FS}{FILE_NAME})) { + print STDERR "warning: it looks like you're running the $project "; + print STDERR "project, but no file system disk is present\n"; + } + if ($project eq 'vm' && !defined $disks{SWAP}{FILE_NAME}) { + print STDERR "warning: it looks like you're running the $project "; + print STDERR "project, but no swap disk is present\n"; + } + } +} + +# Prepare the scratch disk for gets and puts. +sub prepare_scratch_disk { + # Copy the files to put onto the scratch disk. + put_scratch_file ($_->[0]) foreach @puts; + + # Make sure the scratch disk is big enough to get big files. + extend_disk ($disks{SCRATCH}, @gets * 1024 * 1024) if @gets; +} + +# Read "get" files from the scratch disk. +sub finish_scratch_disk { + # We need to start reading the scratch disk from the beginning again. + if (@gets) { + close ($disks{SCRATCH}{HANDLE}); + undef ($disks{SCRATCH}{HANDLE}); + } + + # Read each file. + # If reading fails, delete that file and all subsequent files. + my ($ok) = 1; + foreach my $get (@gets) { + my ($name) = defined ($get->[1]) ? $get->[1] : $get->[0]; + $ok &&= get_scratch_file ($name); + if (!$ok) { + die "$name: unlink: $!\n" if !unlink ($name) && !$!{ENOENT}; + } + } +} + +# put_scratch_file($file). +# +# Copies $file into the scratch disk. +sub put_scratch_file { + my ($put_file_name) = @_; + my ($disk_handle, $disk_file_name) = open_disk ($disks{SCRATCH}); + + print "Copying $put_file_name into $disk_file_name...\n"; + + # Write metadata sector, which consists of a 4-byte signature + # followed by the file size. + stat $put_file_name or die "$put_file_name: stat: $!\n"; + my ($size) = -s _; + my ($metadata) = pack ("a4 V x504", "PUT\0", $size); + write_fully ($disk_handle, $disk_file_name, $metadata); + + # Copy file data. + my ($put_handle); + sysopen ($put_handle, $put_file_name, O_RDONLY) + or die "$put_file_name: open: $!\n"; + copy_file ($put_handle, $put_file_name, $disk_handle, $disk_file_name, + $size); + 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($file). +# +# Copies from the scratch disk to $file. +# Returns 1 if successful, 0 on failure. +sub get_scratch_file { + my ($get_file_name) = @_; + my ($disk_handle, $disk_file_name) = open_disk ($disks{SCRATCH}); + + print "Copying $get_file_name out of $disk_file_name...\n"; + + # Read metadata sector, which has a 4-byte signature followed by + # the file size. + my ($metadata) = read_fully ($disk_handle, $disk_file_name, 512); + my ($signature, $size) = unpack ("a4 V", $metadata); + (print STDERR "bad signature on scratch disk--did Pintos run fail?\n"), + return 0 + if $signature ne "GET\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 1; +} + +# Prepares the arguments to pass to the Pintos kernel, +# and then write them into Pintos bootloader. +sub prepare_arguments { + my (@args); + push (@args, shift (@kernel_args)) + while @kernel_args && $kernel_args[0] =~ /^-/; + push (@args, 'put', defined $_->[1] ? $_->[1] : $_->[0]) foreach @puts; + push (@args, @kernel_args); + push (@args, 'get', $_->[0]) foreach @gets; + write_cmd_line ($disks{OS}, @args); +} + +# Writes @args into the Pintos bootloader at the beginning of $disk. +sub write_cmd_line { + my ($disk, @args) = @_; + + # Figure out command line to write. + my ($arg_cnt) = pack ("V", scalar (@args)); + my ($args) = join ('', map ("$_\0", @args)); + die "command line exceeds 128 bytes" if length ($args) > 128; + $args .= "\0" x (128 - length ($args)); + + # Write command line. + my ($handle, $file_name) = open_disk_copy ($disk); + print "Writing command line to $file_name...\n"; + sysseek ($handle, 0x17a, 0) == 0x17a or die "$file_name: seek: $!\n"; + syswrite ($handle, "$arg_cnt$args") or die "$file_name: write: $!\n"; +} + +# 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, address=0xf0000 +vgaromimage: file=\$BXSHARE/VGABIOS-lgpl-latest +boot: disk +cpu: ips=1000000 +megs: $mem +log: bochsout.txt +panic: action=fatal +EOF + print BOCHSRC "gdbstub: enabled=1\n" if $debug eq 'gdb'; + print BOCHSRC "clock: sync=", $realtime ? 'realtime' : 'none', + ", time0=0\n"; + print_bochs_disk_line ("ata0-master", 0); + print_bochs_disk_line ("ata0-slave", 1); + if (defined ($disks_by_iface[2]{FILE_NAME}) + || defined ($disks_by_iface[3]{FILE_NAME})) { + print BOCHSRC "ata1: enabled=1, ioaddr1=0x170, ", + "ioaddr2=0x370, irq=15\n"; + print_bochs_disk_line ("ata1-master", 2); + print_bochs_disk_line ("ata1-slave", 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"; + } +} + +# print_bochs_disk_line($device, $iface) +# +# If IDE interface $iface has a disk attached, prints a bochsrc.txt +# line for attaching it to $device. +sub print_bochs_disk_line { + my ($device, $iface) = @_; + my ($disk) = $disks_by_iface[$iface]; + my ($file) = $disk->{FILE_NAME}; + if (defined $file) { + my (%geom) = disk_geometry ($disk); + print BOCHSRC "$device: type=disk, path=$file, 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'); + for my $iface (0...3) { + my ($option) = ('-hda', '-hdb', '-hdc', '-hdd')[$iface]; + push (@cmd, $option, $disks_by_iface[$iface]{FILE_NAME}) + if defined $disks_by_iface[$iface]{FILE_NAME}; + } + 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; + + # Memory size must be multiple of 4. + $mem = int (($mem + 3) / 4) * 4; + + 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 ($disk) = $disks_by_iface[$i]; + my ($dsk) = $disk->{FILE_NAME}; + next 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 ($disk); + 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. + +# open_disk($disk) +# +# Opens $disk, if it is not already open, and returns its file handle +# and file name. +sub open_disk { + my ($disk) = @_; + if (!defined ($disk->{HANDLE})) { + if ($disk->{FILE_NAME}) { + sysopen ($disk->{HANDLE}, $disk->{FILE_NAME}, O_RDWR) + or die "$disk->{FILE_NAME}: open: $!\n"; + } else { + ($disk->{HANDLE}, $disk->{FILE_NAME}) = tempfile (UNLINK => 1, + SUFFIX => '.dsk'); + } + } + return ($disk->{HANDLE}, $disk->{FILE_NAME}); +} + +# open_disk_copy($disk) +# +# Makes a temporary copy of $disk and returns its file handle and file name. +sub open_disk_copy { + my ($disk) = @_; + die if !$disk->{FILE_NAME}; + + my ($orig_handle, $orig_file_name) = open_disk ($disk); + my ($cp_handle, $cp_file_name) = tempfile (UNLINK => 1, SUFFIX => '.dsk'); + copy_file ($orig_handle, $orig_file_name, $cp_handle, $cp_file_name, + -s $orig_handle); + return ($disk->{HANDLE}, $disk->{FILE_NAME}) = ($cp_handle, $cp_file_name); +} + +# extend_disk($disk, $size) +# +# Extends $disk, if necessary, so that it is at least $size bytes +# long. +sub extend_disk { + my ($disk, $size) = @_; + my ($handle, $file_name) = open_disk ($disk); + 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 ($disk) = @_; + my ($file) = $disk->{FILE_NAME}; + my ($size) = -s $file; + die "$file: stat: $!\n" if !defined $size; + die "$file: size not a multiple of 512 bytes\n" if $size % 512; + my ($cyl_size) = 512 * 16 * 63; + my ($cylinders) = ceil ($size / $cyl_size); + extend_disk ($disk, $cylinders * $cyl_size) if $size % $cyl_size; + + return (CAPACITY => $size / 512, + C => $cylinders, + H => 16, + S => 63); +} + +# 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; +} + +# 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. + 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 ($?) == SIGVTALRM ()) { + 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) = `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) { + 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); +} +# Thanks Klas + + +#sub SIGVTALRM { +sub get_vtalarm{ + if(defined &SIGALARM){ + return SIGVTALRM(); + } + 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; +} diff --git a/src/utils/pintos-gdb b/src/utils/pintos-gdb new file mode 100644 index 0000000..4ef38d3 --- /dev/null +++ b/src/utils/pintos-gdb @@ -0,0 +1,20 @@ +#! /bin/sh + +# Path to GDB macros file. Customize for your site. +GDBMACROS=/usr/class/cs140/pintos/pintos/src/misc/gdb-macros + +# Choose correct GDB. +if command -v i386-elf-gdb >/dev/null 2>&1; then + GDB=i386-elf-gdb +else + GDB=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 diff --git a/src/utils/pintos-mkdisk b/src/utils/pintos-mkdisk new file mode 100644 index 0000000..662b2e5 --- /dev/null +++ b/src/utils/pintos-mkdisk @@ -0,0 +1,37 @@ +#! /usr/bin/perl + +use strict; +use warnings; +use POSIX; +use Getopt::Long; +use Fcntl 'SEEK_SET'; + +GetOptions ("h|help" => sub { usage (0); }) + or exit 1; +usage (1) if @ARGV != 2; + +my ($disk, $mb) = @ARGV; +die "$disk: already exists\n" if -e $disk; +die "\"$mb\" is not a valid size in megabytes\n" + if $mb <= 0 || $mb > 1024 || $mb !~ /^\d+(\.\d+)?|\.\d+/; + +my ($cyl_cnt) = ceil ($mb * 2); +my ($cyl_bytes) = 512 * 16 * 63; +my ($bytes) = $cyl_bytes * $cyl_cnt; + +open (DISK, '>', $disk) or die "$disk: create: $!\n"; +sysseek (DISK, $bytes - 1, SEEK_SET) or die "$disk: seek: $!\n"; +syswrite (DISK, "\0", 1) == 1 or die "$disk: write: $!\n"; +close (DISK) or die "$disk: close: $!\n"; + +sub usage { + print <<'EOF'; +pintos-mkdisk, a utility for creating Pintos virtual disks +Usage: pintos DISKFILE MB +where DISKFILE is the file to use for the disk + and MB is the disk size in (approximate) megabytes. +Options: + -h, --help Display this help message. +EOF + exit (@_); +} diff --git a/src/utils/setitimer-helper.c b/src/utils/setitimer-helper.c new file mode 100644 index 0000000..772d736 --- /dev/null +++ b/src/utils/setitimer-helper.c @@ -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; +} diff --git a/src/utils/squish-pty.c b/src/utils/squish-pty.c new file mode 100644 index 0000000..c8375a5 --- /dev/null +++ b/src/utils/squish-pty.c @@ -0,0 +1,355 @@ +#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 <stropts.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 (call); + } + else + return true; + } + else + { + if (retval == 0) + { + close (*fd); + *fd = -1; + return true; + } + else + fail_io (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); + + /* System V implementations need STREAMS configuration for the + slave. */ + if (isastream (slave)) + { + if (ioctl (slave, I_PUSH, "ptem") < 0 + || ioctl (slave, I_PUSH, "ldterm") < 0) + fail_io ("ioctl"); + } + + /* 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"); + } +} diff --git a/src/utils/squish-unix.c b/src/utils/squish-unix.c new file mode 100644 index 0000000..9d9aa42 --- /dev/null +++ b/src/utils/squish-unix.c @@ -0,0 +1,354 @@ +#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 <stropts.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> + + +/* AF_LOCAL is not defined on solaris */ +#if !defined(AF_LOCAL) +#define AF_LOCAL AF_UNIX +#endif +#if !defined(PF_LOCAL) +#define PF_LOCAL PF_UNIX +#endif + + +/* solaris doesn't have SUN_LEN */ +//#ifndef SUN_LEN +//#define SUN_LEN(sa) ( strlen((sa)->sun_path) + \ +// (size_t)(((struct sockaddr_un*)0)->sun_path) ) +//#endif + +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 (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 vsun; + 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. */ + vsun.sun_family = AF_LOCAL; + strncpy (vsun.sun_path, argv[1], sizeof vsun.sun_path); + vsun.sun_path[sizeof vsun.sun_path - 1] = '\0'; + if (unlink (vsun.sun_path) < 0 && errno != ENOENT) + fail_io ("unlink"); + if (bind (sock, (struct sockaddr *) &vsun, + (offsetof (struct sockaddr_un, sun_path) + + strlen (vsun.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"); + } +} |
