107 points · by Tomte · 2y ago · 167 comments
Finally got enough information and realized that the padding of a specific object was wrong (GC expected 16 bytes, object was 12 bytes). This caused dozens of other corruption bugs to disappear that we didn't even think were GC related.
Linux/x86-64 expects the stack to always be 16 byte aligned (although the ABI documentation at the time didn't make this assumption very clear). OCaml called into C with a non-aligned stack. GCC-generated code, assuming the stack was 16 byte aligned, used some strange Intel AVX instruction that only works on aligned data, unlike every other Intel instruction ever that can work on any alignment (albeit maybe more slowly).
This manifested itself as rare and totally unreproducible crashes (because stack alignment differed between runs). It was a bit of a nightmare to solve.
https://unrealcommunity.wiki/garbage-collection-36d1da
It works fine because most RAM in games is consumed by assets that don't need to be scanned.
There would also be a debugger allowing to reproduce and catch this in an easier way.
https://github.com/oracle/graal/blob/master/substratevm/src/...
It gets compiled to native code for use. It's actually a bit of a dialect of Java because of course, you need low level memory and stack access. So you can see at parts there is use of special APIs that get compiled to things like stack allocations, so it can avoid allocating on the heap whilst working with it. Even so the "business logic" of a GC can be easily seen here, especially if you don't know C++.
Nothing wrong with a large file. The editor should be able to help you navigate and see the file without the size being a concern at all.
I’m honestly surprised there doesn’t have exist an editor/language that abstracts away the concept of source code files completely. I assume that there is a good chance that in 50 years time we won’t be coding using collections of text files.
[1] http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom...
Were there other technologies that do the same thing? Sure. Were they better? In some cases. Was Java really the "first" by whatever metric? No.
But Java is where the world changed, it just is.
It also seems you are forgetting just how bad early Java was, from a programming and user standpoint. Java errors like NullPointerException became a meme because they were so prevalent in user space, and required so much energy and time to get things working. As a result, people typically refused to update any part of Java once their app was working, to avoid breaking things. And that was _if_ the install was registered with a package manager or Windows Update so updates could be reported.
The things that people build using “idiomatic Java” are scary.
Java is my favorite language, but this is simply untrue. Many people are confused about how object references work, problems with null are very common, generic type erasure can be _very_ confusing, and there are plenty of other rough edges.
That said, Java does get a lot of undeserved hate. It's really quite a pleasant language and it has evolved a lot over the last 10 years.
I like it because it's comprehensively organized. I mean it does everything it should and does it a nice orderly way. The whole class system and c-like system, all together, works good. And addresses everything I want it to address.
And it does that without adding a bunch of crap. Or at least I find that crap easy to ignore. But ya, they do seem to be adding a lot of crap.
In a nutshell, it's a nice neat system. Python is a mess, comparatively.
I'm looking for a new language tho. Orderly and comprehensive like Java, but succincter.
Are you referring to the newer language features? I've personally really enjoyed what's been added and felt that it's unobtrusive, though I haven't been able to use an LTS newer than 17 yet.
Alternativly python with it's typechecker in strict mode is quite organized. Though poorly typed outside dependencies are common. And ofcourse performance is much worse.
C++ is much more scary than Java in a “shoot yourself in the foot” kind of way.
INTERCAL is much more scary than Java in a “this is impossible to understand code” kind of way.
Haskell is much more scary than Java in a “this language has FP constructs” kind of way.
So why is Java scary?
Java is great. Solid ecosystem, solid performance, decent memory safety story, tons of production experience, etc.
And don't get me started on dependency injection systems like Guice. @Inject just means I have no way of knowing the type of an object or how it is initialized without sifting through the entire code base looking for an @Provides. And even then I can never be sure.
There's a lot of Internet trolls that like to bash it and influencers e.g. on Youtube that like to use it to look hip.
It's less about the facts and more about it being the biggest target they can hit.
Coincidentally their religion is called Javascript and according to them there can only be 1 Java.
That is array of cat is a subtype of array of animal. And a function Foo taking an array of animals and appending a dog is legal. Because array of cat is a subtype of array of animal, you can pass an array of cats to foo and append a dog. I believe this causes a runtime type exception, in a type-checked language without using any dangerous casts.
I kind of assume modern java has addressed this somehow, I would love to hear how.
I am personally very excited about a new state-of-the-art GC with no dependencies that is easy to embed called Whippet. The project has received grant funding through NLnet to finish implementation: https://nlnet.nl/project/Whippet/
And sure enough, I had introduced a few bugs along the way. Here is a part of just one commit message:
> NoLeak-InsertionSort.cool exposed a problem where we make a copy of a prototype object to pass it as `this` to the constructor. But while evaluating all the other constructor parameters the copy gets promoted to Old Area. As a result any assignments the constructor makes end up recorded in the assignment stack. So that the referenced objects survive the next minor collection whereas they shouldn't have otherwise.
[1]: https://theory.stanford.edu/~aiken/software/cooldist/lib/tra...
[2]: https://github.com/mykolav/coollang-2020-fs/blob/master/src/...
My lisp's garbage collector works by scanning the stack for pointers. I neglected to spill the registers onto the stack and it led to such nonsensical problems that I'm not even sure how I debugged it. I think my mind has blocked out the experience as a bad memory. I've gotten into the habit of hacking in a call into the garbage collector directly into the eval and cons of debug builds just to stress the garbage collector as much as possible and try to find corruptions near their sources.
You have to instigate a GC torture test as part of your testing, combined with a way of detecting use-after-free. (An obvious way is to reset the type of freed objects, so any use of such an object runs into type mismatches.)
A GC torture tests causes the collection routine to be called often, like after every allocation. If an object is allocated, and now held only in an unspilled register, and then another object is allocated; that first object will be wrongly freed. This is what we want: reproduce the problem, and then hopefully detect it.
If you're garbage collecting underneath a compiler that doesn't know about garbage collection, you have to worry about not only values held in registers not being spilled, but values that are optimized away entirely, which your garbage collector has to see.
For instance:
obj foo_create(obj param)
{
struct foo_object *foo = malloc(sizeof *fo);
foo->bar_attribute = param;
return create_heap_object(foo_type, foo);
}
The problem is that param has no next use after it is assigned to bar_attribute; as far as the optimizer is concerned, it is now a dead variable. Whatever register it occupied can be reused for something else.Let's assume our garbage collector is conservative only w.r.t. stack scanning. Heap objects are traced precisely. We are not scanning every malloc object in existence, in other words, and so, the bar_attribute is not visible to the garbage collector.
Once we call create_heap_object(foo_type, foo), the foo_object structure becomes hooked up to a garbage-collected heap object, and then it is visible to the garbage collector. The foo_type has garbage collector hooks for traversing the "struct foo_object".
Problem is, create_heap_object calls into the garbage collection module to allocate a new heap object, and that can trigger GC. When GC runs, it can wrongly collect the param object.
This can happen if the function has a caller which itself has let go of the param object, like:
obj caller(obj cparam)
{
obj tparam = transform_somehow(cparam);
obj foo = foo_create(tparam);
return foo;
}
Again, tparam has no next use, and so it can cease to exist in this stack frame the moment that foo_create is called. I.e. the only reference to tparam in the entire program is the activation frame of foo_create. Scanning the stack of caller will not find it.Will the code be correct if I ensure that every value on the stack can be recognized by the garbage collector?
If not, then I suppose the way to avoid those issues is to tell the compiler the variable is used somehow. There's the volatile keyword and also lots of compiler attributes I can use. I'm finding it pretty difficult to determine which variables need to be marked this way though.
What is the proper discipline? How did you solve the problem?
I compile with strict aliasing disabled because of problems like these... Maybe I need to disable more optimizations.
They are very accessible and only assume you have light C++ background.
https://www.youtube.com/watch?v=8i1Nv7wGsjk&list=PLpUkQYy-K8... (can be listened at 1.5 speed)
*i.e. all the "unboxed" primitives discussed in the original post.
Great lad to work with as well, open minded to various angles and whole stack from browser experience to deployment.
Now, suppose I were designing a language where data is always owned by at most one thread. I can skip making the ref counter an atomic variable, and with some help of the language do reference counting at compile time: would I still benefit from the complexity of a tracing GC if my goal is performance and predictable latency?
I want to have automatic memory management for both kernel and apps. Creating a concurrent tracing GC that walks the entire user and kernel space sounds incredibly more complicated than just inc/dec'ing a counter and freeing if it reaches zero (again, assuming only one thread can access a single object)
I know that I would have to add language support for weak pointers or forbid cyclic references altogether, but I wonder if the dislike for reference counting only exists because it doesn't work well for data that's shared across threads.
EDIT: thanks all, you have brought excellent arguments and you have convinced me. In fact, in this actor-based OS I am working on, GC+arena based allocation per actor might be the most performing approach. GC collection can happen in the scheduler between messages (so becomes virtually pauseless), and when an actor terminates, just reclaim the entire arena.
Problems with refcounting:
1. You leak cycles. Given the point of a memory management scheme is to reliably not leak, this is a major weakness. Cycles are very common and natural things to find in heaps, and even if you avoid them they can easily be introduced years later by people you will never meet who weren't aware of the entire heap topology. You say you'd just "forbid cyclic references": how will you do that? Require everything to be written in Rust?
2. Every object gets bigger, as it must store a reference. This increases memory usage and reduces locality. With a GC it's possible to squeeze the overhead down to a vtable pointer (required anyway in most cases) and then a few bits on top!
3. All the incs/decs bloat your code, creating a form of pervasive slowness that doesn't show up in profilers except in hot loops. This tempts you to micro-optimize add/decrefs, but that increases the chance of mistakes.
4. Requires a very consistent protocol for how and when references are taken and released. The details here can get complicated. For example do containers add/decref for you, or do they expect you to do that?
5. You are exposed to use-after-free bugs, which are a major source of security holes.
There are probably more. And obviously the restriction to not use threads is catastrophic for any system that cares about performance.
The problem with having the ability to hold managed pointers from kernel<->userspace (whether using rc or gc) is that a process might be malicious or arbitrarily buggy, in the standard OS model. It means you have to be able to kill the process and release all its resources, which means the kernel must know where all the references to kernel-side objects are coming from so they can be removed on kill.
To allow object graphs to span the user/kernel space boundary therefore requires the kernel to mandate the use of a specific compiler that's a part of the TCB (i.e. a part of the kernel itself). That radically changes the design of the whole OS. In particular you cannot implement a UNIX that way.
There's also a problem when taking a reference to the contents of an object - that reference can survive the release of the object.
If you want predictable, you want your GC to run either in constant time slice, or an upper-bounded timeslice.
Deferred refcounts can become quite complex if you want to avoid "I have just released last reference to something that contained a lot of other referenced" (there are some funny threads where Rust users discover that they sometimes need to spin an extra thread to not have effective "stop the world" XD).
So instead common approach is tracing GC with some form timesliced running collector, guaranteeing that time taken from mutator will be upper-bounded. For example, instead of stopping the world, concurrent GC will usually only require a synchronization point. Sometimes it also means that the collector will be given explicit timeslice to ensure that there's certain amount of work being done - it's all tradeoffs based on how much throughput and latency you want.
You can speed up tracing collectors through things like escape analysis and 1bit reference counting (for example, you set a bit if a new reference is passed outside of current scope, every object without bit set can be assumed to have all referenced contained in given scope, etc).
Reference counting is a lot more complicated! It turns every read into a write.
> [...] if my goal is performance and predictable latency?
Reference counters don't have predictable latency: a single reference decrement can lead to an arbitrary amount of follow up work, like more decrements and deallocations.
Performance of reference counting isn't generally better than that of garbage collectors. (Especially since you still need a backup solution to deal with cycles.)
Figuring out a lot of your memory management at compile time is definitely a win. But doesn't really have much to do with reference counting.
Why? Maybe it's crucial to the story, but I am exploring Rust-like single ownership semantics.
You would have to "write" only when you create a new reference to something, or the reference is destroyed. But it wouldn't turn any read into a write, no?
Also, every time you read a pointer you are creating a new reference. That's what turns "every read into a write". You are correct that it's not actually every read, it's just that every small block that reads the value will also write over it.
Not exactly; it turns every passing of a reference, even when it's going to be used only for reading (or not used at all, or just passed on further) into a write of the reference count. But if you can read without passing the reference to somewhere else (or if the compiler can prove that the reference the caller has outlives the reference it would have passed), it can omit the write.
And tracing garbage collection is not completely immune to this; some kinds also turn every read into a write (into a card marking table), copying gc periodically rewrites unmodified objects (when moving them during garbage collection), and the tracing itself might need to read cold objects which might even be located on disk (swapped out).
> Reference counters don't have predictable latency: a single reference decrement can lead to an arbitrary amount of follow up work, like more decrements and deallocations.
However, they have a predictable place for that latency: it can only happen when there's a reference decrement (and the amount of extra work at that point is bounded by the size of the graph which can be reached from that reference). It also will not affect other unrelated threads. With a stop-the-world GC, a thread which allocates too much can cause pauses in threads which are not even allocating or releasing memory at that moment.
> Performance of reference counting isn't generally better than that of garbage collectors. (Especially since you still need a backup solution to deal with cycles.)
However, the memory use of reference counting is generally better than that of tracing garbage collectors, since it releases memory as soon as it can be released. That is, tracing garbage collectors trade extra memory use for their speed; giving them more memory (up to a point) means they can do less work, and giving them too little extra memory can make them much slower.
> Figuring out a lot of your memory management at compile time is definitely a win. But doesn't really have much to do with reference counting.
It does, because it can help reduce the cost of reference counting (by eliding most of the reference count manipulation when it's not necessary).
Yes, if you compare an implementation of reference counting that doesn't stop the world with an implementation of GC that does explicitly stop the world, you will find that GC stops the world more.
You can push the cleanup work on a queue to do it asynchronously, to bound the amount of work per deref / to even the work out.
But you can play the same games with GC. So this is not specific to reference counting. There are incremental and real time versions of GC.
You can elide some of them using a sort of borrow analysis. But borrowed refs can only be used in certain ways, and so this analysis isn't perfect and can't eliminate all of the unnecessary overhead. This was all hashed out in the 80s and 90s IIRC, before multithreading even became a big issue.
The complex analyses needed to make RC perform well end up destroying the simplicity argument, and even after they still aren't competitive with tracing.
Additionally, data can be borrowed from inside the refcounted wrapper, and used freely within a scope without touching the reference count.
CSP often locks you into a single consumer style of pattern, which is highly problematic and scales poorly for anything that isn't statically partitionable. Once you go to MPMC, you start sharing data which immediately forces you to have proper ARC with the high synchronization cost it entails (even without using atomics, RC forces cacheline eviction between cores meaning it acts as a brutal bottleneck on many-core systems per Amadhal's law).
That's a too severe constraint to be qualified as "just".
While it does a little less, the complexity tradeoff just makes more sense to me.
- Let the compiler automatically free variables that go out of scope (using static analysis to insert free calls).
- Use reference counting when the scope is too hard to determine (fall back on a dynamic check).
https://www.researchgate.net/publication/220752316_A_study_o...
The topic was programming. You switched it to horrific mutilation.
Don't do that.