89 points · by todsacerdoti · 1y ago · 127 comments
It's true that libraries should not abort for a regular, foreseeable error. I fundamentally disagree that they should never abort.
If an invariant (something we believe absolutely must be true) is violated, the only sensible thing to do is abort the process. For example, if you set a pointer to NULL and then half an hour later it's time to store a value in that pointer but somehow it's not NULL anymore: clearly something has gone terribly wrong, either in your logic, or potentially in totally unrelated code in some other library which has scribbled on the heap. If execution is allowed to continue, the resultant behaviour is totally undefined: you might corrupt data, or you might allow a permissions check to pass that should have failed, etc. We can't always detect when something has gone wrong, but when we do, it's irresponsible to drive on or try to return an error.
The definition of unacceptable behaviour is so different. A program exit on an exploitable vulnerability is considered unacceptable. The program must continue running, even though all hope should have been lost by this point!
Meanwhile on the other side of the ocean, it would be unacceptable for a program to enable the complete take over of a system!
Getting the panics out of a rust codebase should much simpler than fuzzing out UB. After a few iterations, there won't be any panics whatsoever.
Honestly what I'm seeing here is essentially that C is being preferred, because it lets you sweep the problem under the rug, because UB is such a diffuse concept with unusual consequences. Whereas a panic is concrete and requires immediate attention, attention that will make the program better in the long run.
But that's not true for safe languages - in Rust, if you set a pointer to not-null, it won't end up as null (unless there is buggy unsafe, but let's ignore that). Instead, the panics are likely to be caused by logic errors. Take the decompressor buffer overflow errors author mentioned - the out-of-bounds writes were caused by a bug bit operations generating wrong array index. In Rust, this would be caught by bounds checker, which is good; but Rust would then abort process, which is bad. A hypothetical language that would throw an exception instead of panic'ing would be much better from library perspective - for example a web server might return 500 on that particular request, but it would stay running otherwise.
Using Result<T, E> - the Rust's rough equivalent to checked exceptions in something like Java - would be the wrong choice here since it effectively forces the client to check and handle invariant violations inside library code - and the client really has no way to handle them other then do the equivalent of 500 Internal Error, so there's no point doing such checks on every call.
Your web server example is uncompelling, because a panic-based abort is not the only thing that can distress your system. The simplest example is if the library code doesn’t terminate, accidentally triggering an infinite loop. Or (better from some perspectives, worse from others) an infinite loop that allocates until you run out of memory, denying service until maybe an out-of-memory killer kills the process. In such scenarios, your system can easily end up in a state you didn’t write code expecting, where everything is just broken in mysterious ways.
No, if you want your web server to be able to return an orderly 500 in as many situations of unforeseen errors as possible, the plain truth is that you need the code that will produce that to run on a different computer (approximate definition, though with some designs it may not quite need to be separate hardware), and that you’ll need various sorts of supervisors to catch deviant states and (attempt to) restore order.
In short: for such an example, you already want tools that can abort a runaway process, so it’s actually not so abnormal for a library to be able to abort itself.
There’s genuinely a lot to be said for deliberately aborting the entire process early, and handling problems from outside the process. It’s not without its drawbacks, but it is compelling for things like web servers.
I would also note that, if you choose to, you can normally catch panics <https://doc.rust-lang.org/std/panic/fn.catch_unwind.html>, and Rust web servers tend to do this.
You seem to be saying that it wouldn't catch 100% of the problems, so catching only 80% is not that useful.
I see that as uncompelling. 80% helps a lot!
> you need the code that will produce that to run on a different computer
Problem is, we're using C, C++ and Rust, because latency and performance matters. Otherwise we'd be using Go or Java.
So in order to do what you're proposing, we'd have to do an outbound call on every link of a large filter/processing chain, serializing, transferring, and parsing the whole request data at each recoverable step.
Imagine you are catching the exception. What are you going to do next? From now on, anything can break, and how do you hope recovering if you couldn't do it right in the first place (that's what caused the panic)? You can have a panic handler, in the same way that you can trap SIGSEGV, for some debugging, but that's about it. If a crash is really problematic, use some process wrapper, and maybe a watchdog. Libraries don't work like that for performance and flexibility reasons, they share address space, but the downside is that if they crash, they take everything else with it.
1. The owner of the process (whoever is compiling the binary) - not the library! - gets to decide whether panics immediately abort or try to unwind in a way that can be handled.
2. A panic is never expected (i.e. it always indicates a bug in the code rather than invalid input or other expected failure conditions), so it's optimized for the success scenario both in terms of syntax and in terms of runtime cost. In practice, it means that syntactically the panic always auto-propagates (whereas you need `try` etc with Result); and the code generated by compiler is zero-cost wrt panics if one never happens, but the unwinding is very slow if a panic does happen.
Abort whatever depends on the invariant, which may be less than the whole process.
Now for some languages it is possible to determine that the state strictly through code analysis, without any runtime boundary enforcement. And I think that safe Rust might be in that category, but unsafe Rust definitely isn't - and whether any given library contains unsafe code is an implementation detail...
Then you return an error and let the caller deal with it.
There is no justification, ever, for a library aborting the caller. Even in the scenario you present, it's still better to let the caller deal with the fallout.
> If execution is allowed to continue, the resultant behaviour is totally undefined: you might corrupt data, or you might allow a permissions check to pass that should have failed, etc.
So? that corrupted data or failed permissions check already happened before the library gets to abort anyway.
Let the caller do whatever they can before the process aborts; don't abort for them before the caller has more context than the library does. If you abort without returning an error to the caller, the caller cannot do things like log "Hey, that previous permission check we allowed might have been allowed by accident".
Your way provides absolutely no upside at all.
No, this is absurd. C libraries generally don't do this either. Instead, they might just have UB instead where as Rust tends to panic. So in practice, your suggestion ends up preferring vulnerabilities as a result of UB versus a DoS.
See: https://news.ycombinator.com/item?id=43300120
Can you show me C libraries you've written that are used by others that follow your strategy of turning broken runtime invariants into error values?
Just to be clear, you are making the argument that when a library call detects an error of the form of unexpected NULL/not-NULL, that they abort immediately?
To be even more clear, I'm not making the argument that the program should proceed as normal after detecting an error (regardless of the type of error).
That is not the argument that I am making which is why I find your "That's absurd" condescension extremely confusing.
Which libraries in widespread use know how to detect all of their possible bugs due to invariant violations and report them as explicit error values?
I'd love to see the API docs for them. "This error value is impossible and this library will never return it. If it does, then there is a bug in the library. Since there are no known bugs related to this invariant violation, this cannot happen."
Nevermind the fact that you're now potentially introducing an error channel into operations that should never actually error. That potentially has performance implications.
Nevermind the fact that now your implementation details (internal runtime invariants are implementation details) have now leaked out into your API. Need a new internal runtime invariant? Now you need to add that fact to the API. Need to remove an invariant? Ah well, you still need to leave that possible error value in your API to avoid breaking your users.
In this world, Vec::index() would need to perform not only a bounds check but also a check that the pointer is not NonNull::dangling(). Sure, RawVec is supposed to guarantee that the pointer will not be dangling when cap is >0, but RawVec could have a bug in it.
I agree that documenting and returning a PtrWasDanglingError error is not good API design. An InternalError for all such cases seems more reasonable. But at some point we need to be able to assume that certain program invariants hold without checking at all (in a release build).
Its only "hard" because languages make it hard and implicit what the std library itself is doing.
At worst, every single "assert" should be an exception.
Not ALL possible invariant but wrong array index is a lot of them? If Rust's Vec::operator[] or allocation (new, default) all returns an Result<T, E>. Then its a matter of adding another invariant to the libraries' error enum.
I don't have anything public really to show this but at my work, our library written in C++ have like gazillions of checks using macros, every single invariant is checked and they all crash at debug and throw exceptions at release.
The idea is to eventually trim them down after its been stabilized? Just kidding! The reality is that it actually caught bugs introduced by changes multiple times so it will probably be there forever.
We're talking about the cases that are already being caught somehow (bounds checks, unwraps, ...). It isn't necessary to detect all possible invariant violations to do something else instead of panic, and it suffices to have the language represent those failures without aborting the program.
I know that a lot of people hate that idea, but I strongly disagree. In any large programs, there are thousands of possible errors, and only a small part of them we actually want to handle in a special way. The rest? They go to "other" category. Being able to handle "other" errors, what Rust calls "panic", significantly improves user experience:
For CLI, print explanation that this is an unexpected failure, mention where the logs were saved, mention where to get support (forum/issue/etc...), and exit.
For cron-like scheduled service, notify oncall of the crash, re-schedule the job with intelligent timeout, then exit.
For web, upload details to observability platform, return 500 to user, then when possible terminate the worker.
and so on... In practical world, unexpected errors are a thing, and good language should support them to make programmers' lives easier.
One unfortunate downside of this ability is that some programmers abuse it, and ignore all the unknown errors instead of handling them properly - this makes a terrible user UX and introduces many bugs.
Also, for my "web services" example, if the worker is not terminated, there is a chance the internal data structures will get corrupted, and further requests, even the ones which used to pass, will now fail. There are ways to mitigate this - ignore some exception groups but unconditionally fail on others; or use try/finally blocks and immutable data to reduce the chance of corruption even in case of unexpected exception. But this code is hard to argue about and hard to test for.
Still, if a feature is not a good idea in some specific circumstances, it's not a reason to remove it altogether.
unwrap and expect aren't "innocuous places where panic is hiding". The whole point of unwrap and expects is that you're effectively saying "Hitting a None/Err here is impossible, so seeing them should be treated as a correctness error".
> a panic!() or an abort() are much more annoying to catch and handle.
By design. If you're hoping to catch a panic, then you're doing it woefully wrong. Catching panics is correct only in extremely niche scenarios.
Panic-free Rust code can sometimes be challenging, if a dependency incorrectly asserts an unwrap/expect, but the Rust community tends to hold itself to a higher standard than that.
Other things,
> Most of it is the low-level nitty-gritty, which Rust is not particularly good at.
I don't feel like this was motivated anywhere, just asserted at the end. My opinion is that Rust gives you more tools to make invalid states unrepresentable - this can drastically lower cognitive burden when working on the code.
> Bounds checks are rarely performed in the compiletime and we have to pay their price at the runtime. This is a significant performance hit for coders.
Rust is extremely good at eliding bounds checks. If you attempt to write C++ in Rust (e.g. a moving pointer/slice) then you're probably going to trip these heuristics up, idiomatic Rust (heavy iterator usage) generally results in fewer bounds checks.
> The ownership model is not particularly useful to coders.
Maybe not useful, but certainly unlikely to be a hindrance. The ownership model generally maps extremely well to the CS101 concept of Input -> Processing -> Output, which coders are (and UIs aren't, if you've ever wondered why its still mostly an unsolved problem in Rust).
You can do raw assembly in Rust too.
Catching panics is correct when the panic would cause unwinding across a FFI boundary. I can't think of anywhere else where I wouldn't be very suspicious seeing a catch_unwind().
The one common thing for all such patterns is that they happen at or near the topmost layer of the app (e.g. around the main loop for GUI apps, or around the request handler for web apps).
Calling them innocuous or being surprised that they can panic suggests this person hasn’t really learned much Rust at all.
// personal experience: participated in Rust core lib float parser implementation, part of which involved porting it directly from c++; implemented safe rust qoi image encoder, bpe text encoder, etc; in all cases they turned out to be the fastest existent out there; in all cases, though, good prior experience with low-level rust was required, especially if doing it without unsafe and trying to avoid most bound checks, so there's that.
Does the global_asm! macro suffice for your use case?
Unsafe Rust is still improving on its ergonomics (handling uninitialized memory) but the current capacity should be enough to implement anything.
If you try to use CRTP + virtual on polymorphic types then one has to wonder if it will work as intended for both use cases (when used as a static object or a polymorphic one).
I'm not the absolute most expert C++ programmer, but I'm no noob. The idea of deliberately introducing dynamic polymorphism only to try to optimize it out seems like a bad idea. It's unnecessarily complicated and confusing. If you want to go fast just use CRTP straight up and forget all about dynamic dispatch and potential cute optimizations.
Edit: I think this explains my objection: https://www.codeproject.com/Tips/537606/Cplusplus-Prefer-Cur... (I found that in the StackOverflow post I linked to above.)
I tend to agree with this, which is why I was happy to discover that No-Panic Rust does appear to be practical: https://blog.reverberate.org/2025/02/03/no-panic-rust.html
The one big difference tho is that in Rust, the end user of the library - i.e. the person compiling the binary of which this library is a part - can decide at that point whether panics unwind like C++ exceptions, or just abort immediately. Conversely, this means that the library should never assume that it can catch panics, even its own internal ones, because it may be compiled with panic=abort.
So it's kinda like C++ exceptions, but libraries can only throw, never catch.
I seen this in basically every "I prefer C for this use case" blog post and its always unconvincing, because C is much worse for safety then Rust, so I always think the author would find other problems with these next tools because its just goal posts moving.
I'd expect the same for rust. You make a safe higher level API. It validates all the inputs and then calls into the private "unsafe parts" implemented in C or assembly. Hopefully you've put enough validation in the high level API so that it will be unlikely to call the low-level API in a way that breaks.
Rewriting is not always an option, so improving one's code security is also something to be aware of.
Having said this and since the thread is about text handling, Microsoft has rewriten DWriteCore in Rust.
tbf, author admits he needed to dive into ASM to work around the C compilers sensible optimisation defaults.
tbf to the author, he does explain that the domain of codecs implementation is niche.
great read ... in the best traditions of the Mike Abrash articles of yesteryear.
About page does not disappoint.
Wow. I will think twice the next time I reach for .at().
MSVC does have a documented checked iterator facility that can be enabled even in release builds: https://learn.microsoft.com/en-us/cpp/standard-library/check....