by jackhalford · 6y ago · 0 comments
I'm currently writing an ATA driver [1], the idea is to implement ext2.
I used to do this in Rust but I switched to zig for maintainability and readability over Rust. It seems that with `comptime` I'm able to make a lot of things optimal.
Overall I have to say kernel programming is _hard_ but very rewarding when it finally works, it's really demystifying computers for me!
[0] https://wiki.osdev.org/Brendan%27s_Multi-tasking_Tutorial
Can you expand on this ? I'm asking out of curiosity because I want to learn a "system" programming language (for whatever definition there is to this term). So far I briefly tried Rust and Nim and found the former more difficult to read. I know nothing about Zig, how would you place it between these two ?
* zig has native support for arbitrary sized integers. In Rust I used to do bitshifts, Now I just have a packed struct of u3/u5/u7 whatever (see `src/pci/pci.zig`). Of course Rust has a bitflags crate but I didn't find it handy, this is a case where native support vs library support means a world of difference.
* zig has native support for freestanding target. I used to have to build with Xargo for cross compiling to a custom target, I also was forced to `[nostd]`, and some features I was using forced me to use nightly Rust. In zig I have a simple `build.zig` and a simple `linker.ld` script, just works.
* zig has nicer pointer handling. A lot of kernel programming is stuff that Rust considers unsafe anyway. It's not uncommon to have to write lines like `unsafe { (ptr as const u8) }` to deref a pointer in Rust, which is a pain because this kind of thing happens all of the time. Also you have to play around with mut a lot like this: `unsafe { &mut (address as mut _)`. It just felt wrong a lot of the time, where in zig you have either `const` or `var` and that's the end of it.
* zig is really fun to write! this is something that comes up often in the community, after years of C it's just very refreshing.
Some things zig is missing:
* Package manager, this is coming soon. [1]
* Missing documentation for inline assembly (I think this part is going to get overhauled, as Andrew Kelley is writing an assembler in zig atm [2]).
I don't know Nim, but I believe it has a garbage collector so it could be tricky to use for kernel programming.
[0] https://github.com/jzck/kernel-rs
Arbitrary sized integers do sound very convenient, although I guess the counterargument would be that they simply can't map to machine types so you'll have to have magic behind the scenes which may not make complete sense in low level languages. Still, C has bitfields in structs which are sort of the same thing so why not.
Pointer handling however I'm not sold on. I'd argue that the very cumbersome pointer handling in Rust is a feature, not a bug. It's explicitly discouraged, and for good reasons. Map your pointer into a clean and safe reference, slice or wrapper object ASAP and leave raw pointers to the messy details of C FFIs and ultra low-level code. If you end up having to mess with raw pointers everywhere in your codebase you're doing it wrong, as far as Rust is concerned.
I think this is reasonable even for kernel code. After all typically you wouldn't dereference register pointers directly in C code because of volatility issues and making it obvious that you're accessing hardware and not RAM (readl/writel or similar), so having a safe wrapper adds no overhead in my experience.
* I don't think that low level code needs to be "messy", and
* I don't think that adding an abstraction on top solves anything complexity wise.
For memory paging I used to have a whole library in Rust that handled hierarchy of page tables with very abstract pagetable classes and interfaces [0]. Now I just have 80 lines of zig that handles everything [1]. I much prefer the latter.
> I think this is reasonable even for kernel code.
It's not, for some of the reasons that Linus doesn't want C++ code in the kernel [2]
[0] https://github.com/gz/rust-x86/blob/28d5839933973e0b639ef354...
[1] https://git.sr.ht/~jzck/kernel/tree/master/src/arch/x86/pagi...
Have a look at Project Oberon, Singularity, Interlisp-D, Smalltalk, Modula-3 Topaz, Blue Bottle (AOS), CosmosOS, lilith (Crystal variant) given that their source is available.
> I don't know Nim, but I believe it has a garbage collector so it could be tricky to use for kernel programming.
You're right. Still good for libraries though (or apps, but that may be outside of "system").
That's really cool.
I apologize if this is a naive question. Might you or someone else elaborate on where arbitrary sized integers are used or necessary in kernel programming? Don't they all ultimately need to get padded out for the CPU registers to work with them anyway?
But I've always had a mental note to go back once it got a bit more stable because I really do like the ideas behind it.
It sounds to me like it's definitely getting there and that's awesome.
If you mean that you don't know any right now, just learn C. This isn't web programming, where everyone is always hopping to the latest fads. C is the lingua franca, the sine qua non of systems programming. It will be a long time before that changes. The C machine model is what everyone is working with anyway. C is small, despite some devious and fun corners of it, and mostly just exposes you to that model and way of interacting with the machine.
You can’t even appreciate the new systems languages unless you have a firm grasp of C and systems programming. They are all a response to C, addendum and proposed evolutions to it.
The part where Rust can get really messy is when you involve generic programing and traits, especially when lifetimes are involved, but I couldn't find any obviously generic code in this codebase.
EDIT: after digging a bit deeper into Zig it looks like it uses C++'s style duck typing for metaprograming instead of a trait-based approach like Rust? It definitely removes some overhead to writing generic code but I'm not sure about readability and maintainability... But I'm going to stop here because I'm about to go full fanboy for Rust.
The main difference between Zig and Rust is a huge disparity in language complexity. Zig is a language that can be fully learned in a day or two. Rust has the same philosophy of "zero-cost abstraction" as C++, i.e. spending a lot of complexity budget to make a low-abstraction language appear as if it has high abstraction. Zig, like C, does not try to give the illusion of abstraction.
There is also the difference in their approach to safety, but that's a complicated subject that ultimately boils down to an empirical question -- which approach is safer? -- which we don't have the requisite data to answer.
We do have the requisite data to answer whether preventing use-after-free is better than not preventing it.
You can argue (not successfully, in my opinion) that it's not worth the loss in productivity to prevent UAF and other memory safety issues, but it's impossible to argue that not trying to prevent UAF is somehow safer.
That being said it does make it even weirder to allow braceless ifs IMO, but that's bikeshedding.
Throw in their plans to add a package manager and it's own make system and it seems to be getting further and further from the C replacement I was interested in.
I have seen both Zig and Swift use the module system very well despite several devs strangely saying its somewhat complicated, but when used for low-level development this makes Zig an interesting language to use for language bindings.
Already importing blas into elixir with it is crazy easy.
The problem is: do you want to maintain full backcompat or are you willing to break things to do it cleanly? If you do the former you end up with something like C++ which retains almost complete compatibility with C (but they you have a lot of baggage to carry around, which may get in the way at times) or you're willing to break things and then why not take the opportunity to improve the syntax and get rid of the cruft?
C is ancient now, its type system and its many quirks are quite far from the state of the art or language design, a modern language wouldn't have to mess with the nonsense that are, for instance, C arrays (including C++ which can't outright remove them but does everything it can to render them obsolete with std::vector and std::array).
An other big problem with C interop for newer languages is that while C itself is relatively small and easy the C preprocessor isn't. That's usually where the friction is, because if you want to maintain compatibility with C macros you have to choice but to implement the language syntax wholesale.
Note that Objective-C and C++ are extensions to the C language, and both started as pre-processors that would generate C code.
Also C wasn't the first on its domain, just got lucky that UNIX got widespread adoption and then found its way outside UNIX, just like JavaScript eventually found a way outside the browser.
Because extending or improving a language nearly always means breaking compatibility. Nearly every language is "stuck in a local optimum". To get out of it, you have to kill assumptions of the language that lead to this local optimum.
Also it takes a lot more work to convince other people to adapt my changes than to write an implementation of a language. Add to this the fact that being a good programmer and being a good politician are rather independent skills.
Finally, there do exist issues that cannot be fixed, for example that the official ISO standard of the C language is not freely available (I am aware that there exist drafts in the internet).
Compare this to merely extending a language e.g adding smart pointers - you could always (mistakenly) implicitly fall back onto bad coding practices.
https://www.youtube.com/watch?v=Gv2I7qTux7g
(the title & abstract in the youtube description is the one I gave for the RFP; I ended up going in a slightly different direction than it once I actually made the talk)
C but with the problems fixed.
According to this resource, Zig produces code that is very close to the hand written assembly for the simple use case of outputing "hello world" on the stdout.
This is to be taken with a grain of salt though, as of course, caring about the assembly output is a spectacular case of premature optimization. I guess it tells a bit about the goal of Zig as a low-level programming language though.
I don't agree! at least for operating systems.
Consider that some operating system code may be run a million times per second, on a million different machines (e.g: block system IO on linux). We very much want our assembly to be pristine in this case.
I also like the idea of "optimality" brought forward by zig. In the post you link, there's an ideal hello_world in asm, can we have a higher level language that doesn't sacrifice this ideal achieved by assembly?
Consider that some network cards are now capable of 400Gibps, and modern OSes are not capable of handling these linerate. I strongly believe the bottleneck should be in the hardware, if the software can't max out your hardware then your software has failed.
I like that zig focuses on optimality.
I would believe that most of the time of a processor is dedicated to run userspace code, not OS code (regarding to the work that must be done). At the end of the day, the OS is "only" a scheduler to share hardware resources between unrelated tasks.
> I like that zig focuses on optimality.
Optimality isn't required in many real world businesses. Optimality is often a tradeoff : with optimality you lose in flexibility. An optimal program with SISD instruction set isn't optimal anymore when SIMD instructions are introduced. Your "optimal" asm program is still optimal on x86, but also totally obsolete because it cannot use the latest NEON instructions from ARM or 64bit instructions.
This is a hobgoblin. Assembly output of a compiler is the very baseline of performance. It requires no effort on behalf of the programmer (aside from learning a language).
Now, if you're skimming the assembly after every compilation and, say, fuzzing your implementation to coax the compiler to emit the best possible assembly... that's probably premature. If you're writing inline assembly before doing a higher level implementation, that's probably premature.
But choosing a language on the basis of its performance:effort ratio is downright pragmatic.
Can be important for kernel stuff.
Admittedly I don't know much about Zig, but it's good to see people investigating languages other than C. I'm still not convinced of Rust's merits in this area, we'll see how this develops with time.
ps: I've updated my readme with a few references