Skip to content

11c · cat

Released Thu Sep 24, in class

This is the README OSlings gives every student for 11c_cat (oslings lesson shows it). The starter code is not published here: it reaches you through OSlings, in class on the class network. Back to All Exercises.

Learn → Understand → Implement. The first command that touches real files. By the end you'll know why read is allowed to hand you less than you asked for, and why every program in this course is built around a buffer that never grows.

Learn

cat is short for concatenate. It copies files to standard output, one after another, and that is genuinely all it does:

$ cat notes.txt              # print one file
the first line
the second line
$ cat a.txt b.txt            # all of a, then all of b, with nothing between
$ cat a.txt b.txt > both     # ...which is how you glue two files together
$ cat                        # no files at all: copy standard input instead
hello         <- you type this and press Enter
hello         <- cat echoes it back

That last form is the one people forget: with no file arguments, cat reads standard input, so it works in the middle of a pipeline. You are about to implement all three behaviors.

Standard input, output, error

Every Unix process starts life with three files already open, named by the small integers 0, 1, and 2:

Number Name ulib constant What it usually is
0 standard input STDIN the keyboard, or the left-hand side of a pipe
1 standard output STDOUT the terminal, or a file after >
2 standard error STDERR the terminal, even when output was redirected

Those integers are file descriptors: indexes into a per-process table the kernel keeps, where each slot points at something readable or writable. The program does not know or care what is behind a descriptor — a file, a terminal, a pipe — it just reads and writes a number. You will build that table yourself in exercise 50k_file_descriptors.

Errors go to descriptor 2 and not 1 for a concrete reason: cat a b > out sends standard output into out, and you do not want the words "cannot open" landing in the middle of your data.

The short-read contract

Here is the rule that this whole exercise exists to teach:

pub fn read(fd: Fd, buf: &mut [u8]) -> Result<usize, Error>

read returns how many bytes it actually read, and it is allowed to return fewer than buf.len(). That is called a short read, and it is not an error and not a bug:

  • The file may only have 40 bytes left in it.
  • The console gives you a line at a time — you asked for 512 bytes and the user pressed Enter after typing 12.
  • A pipe hands over whatever the writer has produced so far.

There is exactly one value that means end of file, and it is 0. So the shape of every copying program ever written is a loop: read some, write exactly that many, repeat until you get 0. A program that reads once and assumes it got everything works on small test files and silently truncates real ones.

The short-write contract, and write_all

write has the mirror-image problem:

pub fn write(fd: Fd, buf: &[u8]) -> Result<usize, Error>

It, too, returns a count, and that count may be less than what you gave it — a short write. Ignoring it drops bytes with no error, no crash, and no clue. That bug is common enough that ulib ships the fix:

pub fn write_all(fd: Fd, buf: &[u8]) -> Result<(), Error>

write_all loops until every byte is gone. Read its source in ulib/src/lib.rs — it is nine lines, and once you have seen them you will never call bare write by accident.

One fixed buffer, forever

The buffer in cat_fd is 512 bytes and it is the only storage this program has. Not "for now" — there is no allocator on rv6: no Vec, no String, no format!, no heap. That array lives on the stack, and the memory cat uses is the same whether the file is 20 bytes or 20 gigabytes. It is not a teaching gimmick; it is what a program looks like when the operating system underneath it is one you are still writing. The kernel is written the same way.

Opening a file

let fd = ulib::open(path, O_RDONLY)?;   // Result<Fd, Error>
...
let _ = ulib::close(fd);

open takes the path as bytes (&[u8], not &str — arguments arrive from exec as raw NUL-terminated bytes, and a UTF-8 check would cost image space) plus flag bits: O_RDONLY, O_CREATE, and friends, the same bits xv6 and rv6 use. close gives the descriptor back; forgetting is a descriptor leak, and since the table is a small fixed array, cat * in a directory of 100 files would run it dry. Close on the failure path too, not just the happy one.

What this file becomes in December

The source you are about to write is not a warm-up version of cat that gets replaced later. In December you will run:

oslings ship cat

That compiles this same file for riscv64gc-unknown-none-elf (no_std, no main, no operating system), flattens the ELF into a raw image, and embeds it in your kernel. Then you boot rv6 and type run cat at the shell you wrote in 52k_userland, and every call in your loop becomes an ecall trapping into the handler you wrote in 43k_traps, landing in the descriptor table you wrote in 50k_file_descriptors, reading from the filesystem you wrote in 40k_filesystem.

Not a port, not a rewrite — the same bytes on disk, recompiled. That is what the ulib façade buys you, and it is why the constraints above are non-negotiable: the moment you reach for a Vec, this file stops being able to make the trip.

Understand

Your file is commands/src/bin/cat.rs. Read all of it before you type anything.

Two lines are the entire dual-target ceremony, and you never touch them:

  • #![cfg_attr(target_os = "none", no_std, no_main)] — opt out of the standard library, but only when the target is bare metal.
  • ulib::main!(run); — becomes an ordinary fn main() on your laptop and the _start symbol rv6's exec jumps to on the kernel.

Everything else is plain Rust with no target-specific code in it at all.

fn run(args: Args) -> i32 is your program. The returned i32 is the exit status: 0 means success, non-zero means something went wrong, and that is the number a shell tests with if cat f; then ....

At the bottom is the #[cfg(test)] mod tests block. That is the contract, it is given to you, and you never edit it. Read it first — it is the most precise statement of what cat must do:

  • copies_a_file_to_stdout — the basic case.
  • concatenates_several_files_in_order — argument order matters, nothing is inserted between files.
  • with_no_arguments_reads_stdin — the no-argument form.
  • a_missing_file_reports_an_error_and_exits_nonzero — the message goes to standard error and the status is 1.
  • a_bad_file_does_not_stop_the_good_ones — a missing file followed by a real one: the real one still comes out, and the status is still 1. An implementation that returns from the loop on the first failure passes the test above and fails this one.
  • handles_content_larger_than_the_buffer — 1500 bytes through a 512-byte buffer. Trace it: read gives 512, then 512, then 476, then 0. Four calls, three writes. A single-read implementation passes every other test in the file and fails this one.

Two honest warnings, because a green test run is not the same as a correct program. The host harness always accepts a whole write, so nothing here can catch you using write instead of write_all. And nothing here inspects the descriptor table, so a missing close costs you nothing either. Your kernel will charge you for both in December. Write them correctly now.

Implement

Fill in the three IMPLEMENT markers in commands/src/bin/cat.rs:

  1. cat_fd — the read/write loop: read into the buffer, stop at 0, write back exactly the bytes you got, propagate errors with ?.
  2. the no-argument case in run — copy STDIN and turn the result into an exit status.
  3. the per-file case in run — open each argument, copy it, close it; on failure report on STDERR and remember a non-zero status without abandoning the remaining files.

Delete each let _ = ...; line as you replace it — those exist only to keep the stub compiling.

Check your work:

oslings run 11c_cat

That is plain cargo test on your own machine — no QEMU, no kernel, nothing to boot. If the tests are green, you're done.

Stuck? oslings hint.