The Linux Kernel Prepares for Rust 1.77 Upgrade
phoronix.com
phoronix.com
One issues I have had with Rust applications is the huge binary size (yes, I know this has improved a bit lately). Is there a good comparison between kernel C and kernel Rust code in this regard?
Downloading 3GB of dependencies is not a thing that happens in the Rust ecosystem. Reality is orders of magnitude smaller than that. Why are you exaggerating so much?
Some people bristle at the thought of external dependencies, but if you want to do common tasks it makes sense to pull in common dependencies. That’s life.
Assuming they're talking about the built size of dependencies that are left lying around after cargo builds a binary, they're really not exaggerating by much. I have no difficulty of believing that there are Rust projects that leave 3GB+ of dependency bloat on your file system after you build them.
To take the last Rust project I built, magic-wormhole.rs [1], the source code I downloaded from Github was 1.6 MB. After running `cargo build --release`, the build directory is now 618 MB and there's another 179 MB in ~/.cargo, for a total of 800 MB used.
All this to build a little command line program that sends and receives files over the network over a simple protocol (build size 14 MB). God forbid I build something actually complicated written in Rust, like a text editor.
Also why those GNU/Linux repos are actually multiple DVDs nowadays.
I'm not sure I understand your point with these, as of course no one ever installs the complete repository (e.g. all of Debian), because there's a ton of software in it you don't need or want. Assuming you mean the installation media, at the very least Arch Linux is still less than 1 GB.
Moreover, I think the point in comparing the behavior of Rust dependencies with other ecosystems (C, C++, Haskell, Python) is that most of this cruft is left behind in the individual directories used to build the software. I occasionally write programs to solve some problem, or for fun, and usually I have to download nothing at all, because I can rely on the dependencies supplied by my system and already installed on behalf of other programs (yes, I'm well aware that this doesn't cover all use cases). Rust is fundamentally not designed to work that way, and the large build sizes and huge dependency trees have a multiplying effect on that foundational issue.
For things like a kernel, it is moot as most deps are simply not possible to use anyway.
When you consider the full ecosystem, you need to really compare it to alternatives in largely managed languages like Java, go, node, etc. those binaries are far larger.
What's an example of this for, say, libcurl? On my system it has a tiny number of recursive dependencies, around a dozen. [0] Furthermore if I want to write a C program that uses libcurl I have to download zero bytes of data ... because it's a shared library that is already installed on my system, since so many programs already use it.
I don't really know the appropriate comparison for Rust. reqwest seems roughly comparable, but it's an HTTP client library, and not a general purpose network client like curl. Obviously curl can do a lot more. Even the list of direct dependencies for reqwest is quite long [1], and it's built on top of another http library [2] that has its own long list of dependencies, a list that includes tokio, no small library itself.
In terms of final binary size, the installed size of the curl package on my system, which includes both the command line tool and development dependencies for libcurl, is 1875.03 KiB.
[0] I'm excluding the dependency on the ca-certificates package, since this only provides the certificate chain for TLS and lots of programs rely on it.
The market and your boss do not care about that. They want tasks X and Y done. You have no time to vet 15 alternatives and pick the most frugal one in terms of binary size. Not to mention that for many tasks you have no more than 3-4 alternatives anyway, and none of them prioritize binary size. What are you going to do? Roll your own? Deadline is looming ever closer, I hope you can live without sleep for several days then.
We all know the ideal theory.
At that point I suspect the biggest culprits are overuse of monomorphisation, and often just more stuff happening compared to equivalent C++ code because the language makes larger code bases more maintainable. I'd also count some niceties in that category like better string formatting or panic handling, which is an insignificant cost in any larger software but appears big in tiny hello-world type programs.
This is also true for everything in general. Having the one best thing for foo isn't as helpful as an array of choices, each with different tradeoffs. You simply choose the one best for your needs. Whether it's cheese at the supermarket, an webserver framework, operating system intrinsics, or command line argument handling. Some things can be standardized and serve as a common base for everyone, but it's challenging to do that without at least one person's requirements. Standards also always feature creep until someone tries to reset it with a new standard which is less complex, but I guess that's a different topic.
Do you want a Doodad, a Gooba or a Wumsy? No idea? Me either. So until I care, I'd rather not be asked to choose. But once I discover that I need something with at least 40% Flounce, I can see that Doodads and Goobas both are rated at 50% Flounce, whereas Wumsy has only 10% Flounce, now we're making an informed choice, it should be easy enough to insist on a Doodad to meet my requirement.
If I measure that Monomorphization is out of hand in my codebase I can use dyn to get that back under control for a fair price, but I think the default here is sound.
Sometimes you can provide `T = Arc/Box<dyn Foo>` where `T: Foo` is required, but only if the trait is designed to be object-safe, not simply by default. If you get to design the trait and all of its consumers yourself, you might have this option, but it's very possible that you're using a library that does not make this possible. You can easily be the first person to bother trying the `dyn` for a trait and running into these limitations.
Besides that, you might not even have that much control of the concrete type used. For example, if you are generating large schemas with serde, serde decides how that code is monomorphized, not you. In contrast, for better or worse, the path of least resistance in Go is to use a reflection-based serialization framework which has notable runtime costs (that may or may not matter to a given project) but successfully avoids compile time and binary size costs. (There are other reasons that Go binaries end up even larger than Rust ones, this just isn't one of them)
Despite Rust's general principle of giving its users informed choices here, I am not aware of any option that does 100% dynamic dispatch for (de)serialization, so in practice this is a largely unavoidable cost in each project that is decided only by how complex the schema is.
It's also only fair to point out that C++ tends to end up in this place too, mitigated only by dynamic linking and not any magical property of the language itself. Even C can head this way because monomorphizing with macros has the same effect, though due to how such code is structured, it's also less likely to be inlined than C++ or Rust.
But of course that's an anti-pattern because they are in reality likely to forever just return Vec<T> and knowing that helps you. My early choice only makes sense if either I can't tell you anything more specific than impl IntoIterator<Item = T> or I already know I intend to make a change later. So these days I almost always write down what exactly is returned unless either I can't name it or no reasonable person would care.
For serde in particular my guess is that if you need lots of dynamism serde is the wrong approach even though it's popular. It might be interesting to build a different project which focuses on dynamic dispatch for the same work and tries to re-use as much of the serde eco-system as possible. Not work which attracts me though.
Because I didn't admit you were getting a Vec, if you actually need a Vec you actually can't just use the one I gave you. You must jump though hoops to turn whatever I gave you into a Vec, bloating your code.
The implementation is pretty clever, it is probably not going to meticulously take my Vec to pieces, throw it away and make you a new one, instead just giving the same Vec. But this trick is fragile, so much better not to even need it.
Turn off the standard library and your binaries can be incredibly small. This is how it’s used in microcontrollers and the Linux Kernel doesn’t use the full standard library either.
There’s panic_immediate_abort unstable setting that makes Rust panics crash as hard as a C segfault, and only then you can get rid of a good chunk of stdlib.
I generally find Rust binaries to be "a few" megabytes if they don't have an async runtime, and a few more if they do. It has never bothered me on an individual program basis, but I can imagine it adding up over an entire distribution with hundreds of individual binaries. I see the very real concern there, but personally I would still not risk ABI hazards just to save on space.
I’ve used Rust for some embedded side projects and I really wish there was a way to just get some unique identifier that I could translate (using debug symbols) to a filename and line number for a crash. This would sort of be possible if you could get the compiler to put the filenames in a different binary section, as you could then just save the address of the string and strip out the actual strings - but today that’s not possible.
FWIW, you can configure this in Cargo.toml:
[profile.release] strip = true
i.e. all programs are larger by 275KB, not larger by 20x.
Rust doesn’t have the privilege of having a system-wide shared stdlib to make hello world executables equally small.
The overhead comes from Rust having more complex type-safe printf, and error handling code for when the print fails. C doesn’t handle the print error, and C doesn’t print stack traces on error. Most of that 200KB Rust overhead is a parser for dwarf debug info to print the stack trace.
linux-vdso.so.1 (0x00007fff25cb8000)
libc.so.6 => /lib64/libc.so.6 (0x00007fe5f08d9000)
/lib64/ld-linux-x86-64.so.2 (0x00007fe5f0ae2000)
And for Rust linux-vdso.so.1 (0x00007ffc109f9000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f8eda404000)
libc.so.6 => /lib64/libc.so.6 (0x00007f8eda222000)
/lib64/ld-linux-x86-64.so.2 (0x00007f8eda4a8000)
Rather Rust has 1 more dynamically linked library than C.Dynamically linked libs rarely contribute heavily to binary bloat
More generally, you statically link something to avoid distribution hassles of various kinds, not because you care about the specific number.
That change will be live on 21st March, so manual strips won't be required after that.
This talks about going to extreme lengths on making the smallest Rust binary possible, 400 bytes when it was written, https://darkcoding.net/software/a-very-small-rust-binary-ind...
The thing is, you lose a lot of nice features when you do this, like panic unwinding, debug symbols, stdlib… for kernel and some embedded development it’s definitely important, but for most use cases, does it matter?
In ye olden days it was common to distribute a binary without debug symbols, but to keep a copy of them for every released build¹. If an application crashed (panicked, signalled, etc.) you got a core dump that you could debug using the stripped binary together with the symbol file. This gave you both smaller binary sizes and full debugging capability at the cost of some extra administration. I'm not sure if this is possible with "stock" Rust, but if you need lean binaries but want to do forensic investigation it's something to look into.
1. https://sourceware.org/gdb/current/onlinedocs/gdb.html/Separ...
1: https://doc.rust-lang.org/cargo/reference/profiles.html#spli...
However, most complaints are about size of “Hello World”, which in Rust is due to libstd always having debug info (to be fixed soon), and panic handling code that includes backtrace printing (because print to stdout can fail).
Printing of backtrace is very bloaty, because it parses and decompresses debug info.
Can you quantify this? How big is too big? Ideally for a real program, and not an experiment to make the tiniest possible program.
On my Windows machine ripgrep rg.exe is just 4.2mb. Making that smaller feels irrelevant.
I’m not convinced that binary size is a real problem. But I’m open to evidence!
I do still own my first computer, an IBM PS/2 Model 50Z, which still has its original floppy drive. Other parts I upgraded -- the 286 was replaced with a 386 SX/Now!, the 30MB ESDI was upgraded to 100MB, and it now has a full 2MB of RAM. I keep the floppy drive because it reads disks that no other floppy drive has been able to read.
I've only used rust nightly for my own projects and didn't give too much thought about rust versions
And you can use clippy to tell you about changes you should make.
For example, in my projects I run this in the CI pipeline:
cargo clippy --all-targets --all-features
and cargo fmt --all --check
In addition to the regular test and build steps.This both means that I follow clippy recommendations and cargo fmt in the first place, and also that my CI tells me about any clippy changes if I didn’t notice them myself as well as any formatting I’m not following. In my main IDE I auto format the code of course. But sometimes I make small changes in vim and don’t run the format step myself so it’s nice to have for that reason as well.
For the integration of Rust into the Linux kernel I imagine it’s a bit more convoluted.
The article is about updating the Rust version the kernel targets where a feature they use (offset_of) was stabilized.
Besides, at this stage, it makes perfect sense for Linux to use unstable Rust features. It was one thing to say Rust should be great for writing kernels, it's another to actually get feedback on how it needs to be better, and that's only possible if the potential improvements are motivated by those who need them and incubated without the constraints of backwards compatibility nor the risks of locking in permanent tech debt.
Rust's unstable feature concept was designed for exactly this kind of freeform evolution and it's working exactly as intended. As for the specific tradeoffs being made in Linux, its contributors are in a much better position to weigh those than we are.
> I estimate it's about ½ hour per 1 million lines, on average.
That being said, Rust for Linux isn't using stable Rust, so they have a higher burden than projects that do.
If you include dependencies then it can happen that a dependency relies on unstable features. In which case you might have to upgrade the library version (if they support the new compiler version). The library might have changed the API by then which would force you to change your code.
Except for the above use case, upgrades to the latest version of the compiler have been painless for me.
Rust's stdlib is maintained with the rest of the language and by the same broad team, so, if you're tweaking unstable feature X, you are also responsible for ensuring the stdlib people using feature X sort that out. I'm not sure if Rust's internal policies mean you shouldn't land a change to the main tree without accompanying stdlib patches, or whether you're only required to give them adequate notice, but either way it's not going out the door in a stable release being incompatible with its own implementation.
This couldn't really work with 3rd party libraries.
Some of the features are essentially perma-unstable, because they're exposing some compiler intrinsics for the library to be able to use. This is the equivalent of things like __builtin_* for C compilers.
> If any of the following conditions are violated, the result is Undefined Behavior:
> * Both the starting and resulting pointer must be either in bounds or one byte past the end of the same allocated object.
> * The computed offset cannot exceed isize::MAX bytes.
> * The offset being in bounds cannot rely on “wrapping around” the address space. That is, the infinite-precision sum must fit in a usize.
> Most platforms fundamentally can’t even construct such an allocation. For instance, no known 64-bit platform can ever serve a request for 263 bytes due to page-table limitations or splitting the address space. However, some 32-bit and 16-bit platforms may successfully serve a request for more than isize::MAX bytes with things like Physical Address Extension. As such, memory acquired directly from allocators or memory mapped files may be too large to handle with this function.
> Consider using wrapping_sub instead if these constraints are difficult to satisfy. The only advantage of this method is that it enables more aggressive compiler optimizations.
If their pointer subtraction uses similar semantics, there might be issues if they want to compare pointers from different allocation objects, are worried about 32-bit or 16-bit platforms, or maybe even consider the performance concerns too worrisome. The Rust I write tends to be a bit higher-level and doesn't require unsafe, so my instinctual reaction to "using unsafe for performance" generally errs on the same of abject terror, but it's a fundamental part of what makes the safe side of abstractions I use possible, and the kernel is probably one of those places that needs to do that sometimes, so I'd reluctantly have to admit I'm probably not qualified to evaluate whether these cases would merit unsafety for performance alone, but the first two concerns sound like legitimate things that the kernel would need to handle.
Any of these type of issue would equally invalidate using unsafe{} to cast the pointer to a reference, which is what non_null! does.
Rust's standard library has three elements
core has stuff you get with the Rust language, like any use of Rust, Rust for Linux has core. You could technically implement Rust without core, or at least, without most of it, but that's not really the Rust language, you've instead made your own weird fork.
[T]::sort_unstable() is a core function which sorts a slice of some Ordered type T but may re-arrange elements despite them comparing equal hence the word "unstable".
alloc depends on an allocator. You may not have an allocator, e.g. you're a tiny embedded controller, in which case you likely don't want and can't use this. Rust for Linux re-implements alloc, basically cloning the "official" alloc and fiddling with it.
Vec::try_reserve() is a feature found in alloc, it tries to allocate enough space to ensure your Vec has a certain amount of capacity beyond its current size, and if not reports it could not.
std further depends on an Operating System, it offers exciting features like knowing what the time is, reading a file, connecting to a remote service over TCP/IP, or making a thread. Rust for Linux does not provide std.
File::create() is a std function which creates files.
The function you were interested in is part of core (although you were looking at its re-export from std) and so yes, it exists in Rust for Linux.
C: 33,351,596 lines
(That's just doing 'wc -l' rather than using any proper code metrics tool)
===============================================================================
Language Files Lines Code Comments Blanks
===============================================================================
C 33553 23772322 17694564 2662642 3415116
C Header 24554 9562920 7395591 1436546 730783
Device Tree 5041 1512839 1240129 76384 196326
ReStructuredText 3473 711669 539971 0 171698
JSON 788 443098 443096 0 2
YAML 3905 433860 352107 16626 65127
GNU Style Assembly 1317 372131 271873 55613 44645
Shell 894 172036 120033 21590 30413
Plain Text 1739 151033 0 123992 27041
Makefile 2946 76889 52985 12355 11549
Python 203 68545 54627 4452 9466
SVG 74 49420 48159 1171 90
Perl 59 43992 34124 4074 5794
Happy 10 6069 5359 0 710
Assembly 5 3319 3065 0 254
C++ 5 2138 1860 61 217
BASH 59 1943 1318 335 290
Unreal Script 5 707 445 158 104
ASN.1 16 660 445 87 128
Autoconf 5 429 373 26 30
LD Script 8 376 288 29 59
CSS 3 295 172 69 54
Gherkin (Cucumber) 1 291 199 58 34
TeX 1 236 156 74 6
XSL 10 200 122 52 26
HEX 2 173 173 0 0
Module-Definition 2 128 113 0 15
C++ Header 2 125 59 55 11
RPM Specfile 1 108 93 1 14
Objective-C 1 89 72 0 17
Vim script 1 42 33 6 3
Markdown 1 36 0 27 9
Automake 3 31 23 3 5
Ruby 1 29 25 0 4
INI 2 13 6 5 2
TOML 1 12 2 9 1
Apache Velocity 1 12 12 0 0
CMake 2 8 8 0 0
-------------------------------------------------------------------------------
Rust 64 12637 9489 1612 1536
|- Markdown 55 8243 808 5557 1878
(Total) 20880 10297 7169 3414
-------------------------------------------------------------------------------
HTML 2 28 22 3 3
|- JavaScript 1 7 7 0 0
(Total) 35 29 3 3
===============================================================================
Total 78760 37400888 28271191 4418115 4711582
===============================================================================
So If we would only count code and not comments, it is only 9489 LoC Rust. Which would be about 0.03% and if we take all lines and not only LoC it would be around 0.05%[0] https://github.com/XAMPPRocky/tokei
[1] https://github.com/torvalds/linux/commit/b401b621758e46812da...
What are the implications of using Rust on building Linux?
That might not apply at a "system's" level but I'm guessing in the massive Linux compilation job with module support you're making a bunch of object files with exported symbols?
(For the curious) https://elephly.net/posts/2017-01-09-bootstrapping-haskell-p...
Yes, the GHC story is also terrible (and just a tad worse than the rust story). The GHC problem is worse largely because the origins of GHC are murky. While it's still possible to get copies of the early GHC versions through the Internet Archive, the code lives firmly in the 1990s and assumes that you have access to long lost Haskell compilers. Turns out that all these Haskell compilers (with the exception of Hugs) have the same kind of problems that GHC has --- only worse because they are even older, depend on binaries of unreleased previous versions, and are really difficult to build with tools from the last two decades.