13c · grep¶
Released Fri Sep 25, in class
This is the README OSlings gives every student for 13c_grep (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. Substring search, the three edge cases that break everybody's first attempt at it, and why a Unix command's exit status is part of its output. This is the last core command exercise (
headis extra credit) — and the one you will most enjoy watching run on your own kernel.
Learn¶
grep reads lines of text and prints the ones that contain a pattern.
That is the entire user-visible behavior. Everything else is edge cases, which is where all the difficulty in Unix commands actually lives.
Vocabulary, because it recurs for the rest of the semester. A line is a
run of bytes ending at a \n; the newline is a separator, not part of the
line, and the last line of a file may have none. Standard input (stdin,
file descriptor 0) is where a command reads when you do not name a file:
grep cat < animals.txt, or the left side of a pipe, ls | grep .rs. The
pattern is what you are looking for — in search code, the needle; the
text you search is the haystack. Those two names are used throughout.
The pattern is a plain string, not a regular expression¶
The grep on your laptop matches regular expressions — ^foo, a.*b,
[0-9]+. That is a second, much larger exercise. Ours matches a fixed string: a
line is selected if the pattern occurs anywhere inside it as a contiguous run
of bytes, exactly as the real one behaves when the pattern has no special
characters. Contiguous is the operative word: contains(b"concatenate",
b"cat") is true, and contains(b"cart", b"cat") is false even though all
three letters are there in order.
Exit status is an output¶
Every program hands the kernel one small integer when it finishes: its exit
status. The shell keeps it in $?, and && and if are built on it — 0
means success and anything else means failure. It is the only value a program
returns that another program can act on without parsing text.
grep uses three of them, and the convention is worth memorizing because
half of all shell scripts depend on it:
| Status | Meaning |
|---|---|
0 |
at least one line matched |
1 |
no line matched, and nothing went wrong |
2 |
something went wrong — bad usage, or a file that would not open |
"Found nothing" is deliberately not an error. It is a successful run that
answers "no", which is why grep -q needle file && echo yes works: status 1
makes && skip the right-hand side. A grep that returned 0 either way would
be useless in a script. In your program the exit status is just the i32 your
run function returns; ulib::main! hands it to exit for you.
Which file did that line come from?¶
Given several files, a bare line of output is ambiguous, so grep prefixes each hit with the file it came from and a colon:
Given exactly one file there is nothing to disambiguate, so there is no
prefix, and reading from stdin there is no filename to print at all. That rule
— prefix only with two or more file operands — is already written for you in
run; you implement the printing it asks for.
Three ways a substring search goes wrong¶
contains is about a dozen lines, and three specific inputs break the obvious
dozen. The first two are guarded against in code that is written for you; the
third is yours to get right. There is a test for each of them:
- The empty needle.
grep '' fileprints every line, including empty ones. An empty string occurs inside every string, at position 0. The skeleton says so explicitly, before anything is scanned. - A needle longer than the haystack. Searching for
abcdefghinabccannot succeed — but the natural loop bound ishaystack.len() - needle.len(), and lengths areusize, an unsigned integer.3 - 8does not go negative: a debug build panics on the spot, a release build wraps to about 18 quintillion and then indexes past the end of the slice, which panics too. The given guard rules this case out before the subtraction, which is why it sits above the loop. - A match at the very end. Looking for
xinabcx, the last start position you must try is index 3 — which is exactlyhaystack.len()minusneedle.len(). So the range of start positions includes its upper bound. In Rust that is0..=n, not0..n. Write..there and you get a grep that silently misses every match ending at the last byte, which is the sort of bug that survives for years.
A panic is a bad way to find any of this out. On your laptop a panic prints a
file, a line, and a message. On rv6 the whole panic handler is six lines long
and prints the single word panic. That is the entire diagnostic — which is
why you get these three cases right here, where cargo test tells you.
One buffer, no allocator, bytes not strings¶
There is no heap in this program. No Vec, no String, no format! — the
kernel you are building has an allocator, but a user program on rv6 has no
malloc to call and no room for one. So:
- Text is
&[u8], never&str. Arguments arrive fromexecas NUL-terminated bytes, and validating UTF-8 would cost image space. - All storage is fixed:
let mut buf = [0u8; 1024];ingrep_fdis the program's entire memory footprint beyond its stack.
ulib::Lines is given to you, because splitting a stream into lines without a
heap is fiddly: a read returns whatever the kernel felt like giving you,
lines straddle the boundaries, and you have to shuffle the leftovers forward.
Lines does that, so this exercise can be about grep and not about ring
buffers. It hands back one line at a time out of that single buffer, refilling
and compacting as it goes, never allocating; a line longer than the buffer
comes back truncated rather than growing it.
let mut buf = [0u8; 1024]; // your storage, on the stack
let mut lines = Lines::new(fd, &mut buf);
while let Some(line) = lines.next_line() {
// `line` has NO trailing newline
}
Lines::new borrows your buffer mutably for as long as the iterator lives.
That is not ceremony — the returned line points into buf, so touching
buf yourself would move the ground under a live reference. In C this is the
classic dangling-pointer bug and nobody catches it; here the compiler simply
refuses. Note that next_line reads from the file only when it needs to.
Stop calling it and the reading stops with you.
You are not being denied a heap to make the exercise harder. You are being shown what a program looks like when the only memory it has is memory it declared.
What happens in December¶
commands/src/bin/grep.rs — this exact file, not a port of it — gets compiled
a second time at the end of the semester:
That builds it for riscv64gc-unknown-none-elf with no_std, flattens the
resulting ELF into a raw image a few kilobytes long, and embeds it in your
kernel. Your shell from exercise 46k then execs it, your file descriptor
table from exercise 50k backs its open and read, and your trap handler from
exercise 43k catches every ecall it makes. The #![cfg_attr(target_os =
"none", no_std, no_main)] line at the top of the file and the
ulib::main!(run) line below it are the entire cost of that portability —
which is why the constraints above are what they are: rv6 loads a program
image into 16 pages, 64 KiB and no more.
Understand¶
Your file is commands/src/bin/grep.rs. Open it and read it top to bottom
before typing anything; most of the program is already written.
The imports name everything you need:
run is given to you, and is worth tracing:
- Fewer than two arguments: usage line on
STDERR, return2. args.get(1)is the pattern — bytes, soOption<&[u8]>.- Exactly two arguments (
grep PATTERN): searchSTDINwith no prefix.Ok(true)becomes 0,Ok(false)becomes 1, an error becomes 2. - Otherwise every remaining argument is a file, opened
O_RDONLY, searched, and closed, withshow_namestrue when there are two or more. A file that will not open is a message onSTDERRand status 2 at the end — but the other files are still searched, as real grep does.
grep_fd returns Result<bool, ulib::Error>, and that bool means did
anything match on this descriptor? run folds those booleans into the exit
status, so forgetting to set found gives you a grep that prints the right
lines and then lies about whether it found them.
At the bottom is #[cfg(test)] mod tests. That block is the contract, it is
given to you, and you never edit it. Read the eight tests first: they say what
correct means far more precisely than this page does.
Implement¶
The two edge cases at the top of contains are given: an empty needle
matches, and a needle longer than the haystack does not, both settled before
any scanning happens. Read those two guards first — the scan you write below
them is only safe because they run first. Then two IMPLEMENT markers, in the
order they appear:
contains— the scan. Try every start position at which the needle still fits, compare the needle's bytes against the haystack's from there, and returntrueon the first start where all of them agree.grep_fd— the match-and-print loop. Walk the lines, keep the matching ones, setfound, print the optionalfilename:prefix, and put back the newline thatLinesstripped.
Each marker's comment lists the details. Delete the let _ = (...); // delete
this line once you implement line in grep_fd once you reach it — it exists
only so the stub compiles before you have written anything.
Check your work:
This is plain cargo test on your own machine. No QEMU, no kernel, nothing to
boot — the same source file will meet your kernel in December.
Stuck? oslings hint.