Back to posts

rsmkswap - An attempt

I made a very premature and immature entry into Rust. What would be the second program I write in Rust? That would be mkswap, the system utility on Linux which prepares a block device for the kernel to be used as swap space. mkswap at its core takes a block device as input, finds its size, finds the page size of the machine, and writes a swap header struct to the beginning of the device denoting its size, the number of pages, the label, a UUID, and some additional tidbits. This header is then read by the kernel during the swapon syscall so it knows what it's working with.

My first attempt was a few days of brute force, reading libraries, docs, and mkswap's source code. Learned a lot and I ended up getting a functioning but fragile program. First build, then perfect it later. True to that maxim, I realized after a short time that with large block sizes there was an integer overflow, classic. Fixed it and all was well. I felt that, though not polished, the program did its duty. I left it and went onto the next one.

It wasn't a happy ending as you can probably guess. Perhaps due to some kernel updates or whatnot, partly Rust updates, the program ended up no longer functioning after a while. I fixed up the Rust issues but when it came time for the swapon syscall it was not able to read the swap header, which is the crux of the program. I recognized that my solution was not as robust as I hoped, nor was it even written in particularly(or at all) idiomatic Rust, since I had no idea what that meant. I hanged up the apron for now, though I am open to revisiting it with a more educated approach, especially to handling raw pointers and slices.

For an amateur and complete beginner in programming and Rust respectively, I had dove into the deep end with a tool which used a specific data structure, written in C, that had to be near-perfectly aligned because it had to be read by the kernel. I was not in any way, shape, or form prepared for that challenge, but I took it on and learned tons and even managed to make an ephemerally working software in the process. Was it a failure? Yes, or alternatively, a temporary setback. Failure can sometimes be more important than success. And it is never bad to be curious and have fun.