83 points · by amichail · 2y ago · 108 comments
Memory Safety Without Lifetime Parameters - https://news.ycombinator.com/item?id=41899828
There is nothing deterministic about how long those calls take, or stack size requirements, especially if they trigger cascade deletions, or are moved into a background thread to avoid such scenarios.
Reference counting optimizations slowly turn into a tracing GC.
The behavior is deterministic enough to be profiled and identified if it actually becomes an issue.
Identifying causes of pressure on a mark-and-sweep style GC is much more difficult, and depends on specialized GC instrumentation, not just a regular profiler.
In practice, you have predictable deallocation patterns for the vast majority of objects. The things that are "young generation" in a GC are the things that get deallocated right away in RC.
Time required to deallocate is straightforwardly proportional to the dataset being freed. This can be a predictable bounded size if you're able to control what is referencing what. If you can't do that, you can't use more constant-time alternatives like memory pools either, because those surprise references would be UAFs.
I've been there when Apple moved Cocoa from GC to ARC, and the UI stutters have disappeared. It's much more palatable to users to have RC cost happening in line with the work application is doing, than have it deferred to cause jank at unexpected times seemingly for no reason.
When a collection in a generational GC occurs, the corresponding generation's heap is scanned for live objects, which are then usually relocated to an older generation. In a most common scenario under generational theory - only few objects survive, and most die in a young/nursery/ephemeral generation (.NET, JVM and other ecosystems have different names for the same thing).
This means that upon finishing the object relocation, the memory region/segment/heap that was previously used can be immediately made available to subsequent allocations. Sometimes it is also zeroed as part of the process, but the cost of such on modern hardware is miniscule.
As a result, the more accurate intuition that applies to most generational GC implementations is that pause time / CPU cost scales with live object count and inter-generational traffic. There is no individual cost for "object deallocation". This process is vastly more efficient than reference counting. The concern for overly high allocation traffic remains, which is why allocation and collection throughput are defining characteristics of GC implementations, alongside average pause duration, frequency, costs imposed by specific design elsewhere, etc.
Allocating and deallocating a complex graph of reference-counted objects costs >10x times more than doing so with a modern GC implementation. I don't know which implementation was used back in the day in Cocoa, but I bet it was nowhere as advanced as what you'd see today in JVMs or .NET.
There is a reason why RC is considered the baby algorithm from automatic memory management algorithms.
Anything that people point out as optimizations, and profiling tools, also exist for the better algorithms.
Most languages with automatic memory management support, also offer primitives to deterministic call sites, if one so desires.
Finally it isn't as if Apple is a genius that managed to revolutionized memory management algorithms, doing in Cocoa what Microsoft was already doing with COM, was the natural way out given Objective-C' GC unsound implementation.
Swift's requirement to stay compatible with Objective-C memory management, naturally required the same approach, the alternative being something like CCW/RCW COM interop from .NET, which understandably they didn't want to go down to, given previous history.
I don’t buy that adding an extension that is safe if you use it will move the needle. But making the language safe wholesale is practical. We should do that instead.
Why?
> We don't need that
You do if you want comprehensive use-after-free protection.
> and the minimal GC support that was in the standard has been removed from C++23.
Not related to what I'm doing. The support you cite is for users of the language to write garbage collectors "on top" of the language. Fil-C++'s garbage collector is hidden in the implementation's guts, "below" the language. Fil-C++ is compliant to C++ whether C++ says that GC is allowed or not.
C++ is usually used when people care about performance, and a GC interferes with that.
I'm not yet sold on Rust, but exploring alternatives for achieving memory safety without needing to put on a GC is commendable.
It should never have been there in first place, because it ignored their requirements, and thus it was never adopted by them or anyone else.
> On the other hand, Fil-C is quite slow. It's ~10x slower than legacy C right now (ranging from 3x slower in the best case, xz decompress, to 20x in the worst case, CPython).
That performance loss is severe and makes the approaches totally uninteresting for a most serious use cases. Most applications written in C or C++ don't get to waste that many cycles.
Note that at the start of this year it was 200x slower. I land speed ups all the time but don’t always update the readme every time I land an optimization. Perf is the main focus of my work on Fil-C right now.
Python does shit like that and it works fine in Fil-C, though I needed to make some minor adjustments a like a 50KB ish patch to CPython.
I think C++ needs a broader "resyntaxing" --- something like what Elixer is to Erlang and Reason is to OCaml. Such a resyntaxing wouldn't change language semantics, but it would allow us to adopt new defaults --- ones that benefit from decades of hindsight. A C++ Elixer wouldn't only mark functions safe by default, but would probably make variables const by default too. And it would be 100% compatible with today's C++, since it would be the same language, merely spelled differently.
The default matters. So long as the language makes it easy to write unsafe code, people will do it and there will be security bugs.
You can upgrade your compiler to version A. It produces safe code. It also produces 500kB of error messages for each of your source files. You will not ship any new builds until you fix all of them.
Or you can pick version B. It compiles all your code with only few errors. It also supports opting-in to multiple safety features.
If your salary depends on your software project, which will you pick?
That‘s the reason for all the problems in the first place.
But this would break backwards compatibility and the C++people do not want that.
An unsafe-by-default language that has some safety features isn't enough to fix memory safety.
Unless you are doing something obscure like testing shotgun-proof footwear, it is a good idea to have an automated system tell you: "ERROR: You are shooting your foot, do not aim at your foot with a shotgun and fire on line 123".
The C and C++ philosophy starts with the premise "programmers know best and will never aim a shotgun at their foot and then fire, that makes no sense haha, why are you talking to me about that? you are silly!". Yet, there are millions of people getting shot in the foot every year and it took a new language to demonstrate that the entire class of nonsense can be prevented.
When I was working with Swift that was not available. Swift wraps "fork" in multi syllable function names and half a dozen variations. But it is (was?) still just fork.
I do not know about the other languages mentioned.
Rust shines on that front. It takes a bit of getting used to, but once you are it is awesome.
I loved C++ back in the day. I have left it there, where it belongs. It was a fantastically successful experiment, but move on now.
https://news.ycombinator.com/item?id=41528124 - Safe C++ (2024-09-13, 68 comments)
...sounds good to me!
If I call into a library and something goes awry I don't want to have to care about the inner workings of that library. Most of the time it's sufficient for me to try/catch that call and if it fails I'll handle it as gracefully as possible at my level.
Acknowledging the error is handling the error even if partially. The point of exceptions is to only acknowledge error that one can/knows how to properly handle
All functions are capable of producing an unbounded set of errors.
(Yes, programming is hard.)
Yes and I'm opposed to such "if err != nil" boilerplate.
It takes statically typed C++ and turns it into dynamically typed language. Throwspec is dead, anything can throw, except when noexcept, then nothing can throw.
It is next to impossible to reason about control flow. Dynamic linking opens whole new dimension of this wormcan. Do you handle exceptions in your constructors? How about constructors of your function arguments?
Not to mention the non-trivial cost in code size, that makes exceptions a non-option for embedded use.
At least delegation (IIUC closer to concatenation as defined in [1]) is currently being implemented, but I can't say how much weight it can actually carry for the OOP efforts.
[1] "On the Notion of Inheritance": https://users.csc.calpoly.edu/~gfisher/classes/530/handouts/...
> These discrepancies are responsible for an impedance mismatch when interfacing the two languages. Most code generators for inter-language bindings aren’t able to represent features of one language in terms of the features of another.
Function overloads are evil evil evil. Requiring some mental gymnastics by the reader to pretend to be the compiler what function is actually called. That sucks.
Take Pattern. One way to look at Pattern is to say that this way we can provide the ad hoc polymorphism of overloading, for functions like str::contains or str::split or str::trim_end_matches -- but as a trait we can see that actually Pattern has discernible semantic properties, clearly a compiled regular expression could be a Pattern for example (and with some feature flags that's exactly correct)
In contrast in C++ there are often functions which use/ abuse overloading to deliver separate features in the same interface, expecting that you'll carefully read the documentation and use the correct feature by passing the right type and number of parameters. Constructors are the worst for this, Rust's Vec::with_capacity gets you a growable array with a certain capacity already allocated ready for use -- C++ does not have such a thing - you must make a std::vector and then separately reserve enough space, but it looks like it might have this feature in its constructor as an overload because the constructor has an overload which is the right shape - however that's actually a very different feature, it will fill the std::vector with default initialized objects, rather than reserving capacity for such objects.
Calling x.some_func() in rust means there is either a type specific function or an impl trait. If more than one option is there rust requires more explicitly calling the types function with x as a parameter.
E.g.
Something::some_func(x)
I’ve never read rust code where I’m entirely guessing which overloaded function is being called. C++ has an entire set of overload resolution rules around this! https://en.cppreference.com/w/cpp/language/overload_resoluti...